将 PHP 的 echo 输出限制为 200 个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7421134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Limiting the output of PHP's echo to 200 characters
提问by Craig
I'm trying to limit my PHP echo
to only 200 characters and then if there are any more replace them with "..."
.
我试图将我的 PHP 限制echo
为仅 200 个字符,然后如果还有更多字符,请将它们替换为"..."
.
How could I modify the following statement to allow this?
我如何修改以下语句以允许这样做?
<?php echo $row['style-info'] ?>
回答by
Well, you could make a custom function:
好吧,您可以创建一个自定义函数:
function custom_echo($x, $length)
{
if(strlen($x)<=$length)
{
echo $x;
}
else
{
$y=substr($x,0,$length) . '...';
echo $y;
}
}
You use it like this:
你像这样使用它:
<?php custom_echo($row['style-info'], 200); ?>
回答by Yeroon
Like this:
像这样:
echo substr($row['style-info'], 0, 200);
Or wrapped in a function:
或者包裹在一个函数中:
function echo_200($str){
echo substr($row['style-info'], 0, 200);
}
echo_200($str);
回答by Sandeep
Not sure why no one mentioned this before -
不知道为什么之前没有人提到这一点——
echo mb_strimwidth("Hello World", 0, 10, "...");
// output: "Hello W..."
More info check - http://php.net/manual/en/function.mb-strimwidth.php
更多信息检查 - http://php.net/manual/en/function.mb-strimwidth.php
回答by Jonnix
<?php echo substr($row['style_info'], 0, 200) .((strlen($row['style_info']) > 200) ? '...' : ''); ?>
回答by Jai
It gives out a string of max 200 characters OR 200 normal characters OR 200 characters followed by '...'
它给出最多 200 个字符或 200 个普通字符或 200 个字符后跟“...”的字符串
$ur_str= (strlen($ur_str) > 200) ? substr($ur_str,0,200).'...' :$ur_str;
回答by Ezenwa Hopekell
This one worked for me and it's also very easy
这个对我有用,也很容易
<?php
$position=14; // Define how many character you want to display.
$message="You are now joining over 2000 current";
$post = substr($message, 0, $position);
echo $post;
echo "...";
?>
回答by wasimv09
this is most easy way for doing that
这是最简单的方法
//substr(string,start,length)
substr("Hello Word", 0, 5);
substr($text, 0, 5);
substr($row['style-info'], 0, 5);
for more detail
了解更多详情
https://www.w3schools.com/php/func_string_substr.asp
https://www.w3schools.com/php/func_string_substr.asp
回答by Luka
string substr ( string $string , int $start [, int $length ] )
回答by gjerich
more flexible way is a function with two parameters:
更灵活的方法是带有两个参数的函数:
function lchar($str,$val){return strlen($str)<=$val?$str:substr($str,0,$val).'...';}
usage:
用法:
echo lchar($str,200);
回答by Ali Umair
function TitleTextLimit($text,$limit=200){
if(strlen($text)<=$limit){
echo $text;
}else{
$text = substr($text,0,$limit) . '...';
echo $text;
}