将PHP的echo输出限制为200个字符

时间:2011-09-14 18:25:06

标签: php

我正在尝试将我的PHP echo限制为仅200个字符,然后再用"..."替换它们。

如何修改以下语句以允许此操作?

<?php echo $row['style-info'] ?>

15 个答案:

答案 0 :(得分:55)

好吧,你可以制作一个自定义功能:

function custom_echo($x, $length)
{
  if(strlen($x)<=$length)
  {
    echo $x;
  }
  else
  {
    $y=substr($x,0,$length) . '...';
    echo $y;
  }
}

你这样使用它:

<?php custom_echo($row['style-info'], 200); ?>

答案 1 :(得分:17)

像这样:

echo substr($row['style-info'], 0, 200);

或包裹在一个函数中:

function echo_200($str){
    echo substr($row['style-info'], 0, 200);
}

echo_200($str);

答案 2 :(得分:8)

不知道为什么之前没有人提到这个 -

echo mb_strimwidth("Hello World", 0, 10, "...");
// output: "Hello W..."

更多信息检查 - http://php.net/manual/en/function.mb-strimwidth.php

答案 3 :(得分:3)

<?php echo substr($row['style_info'], 0, 200) .((strlen($row['style_info']) > 200) ? '...' : ''); ?> 

答案 4 :(得分:3)

它给出一个最多200个字符的字符串或200个普通字符或200个字符后跟&#39; ...&#39;

$ur_str= (strlen($ur_str) > 200) ? substr($ur_str,0,200).'...' :$ur_str;

答案 5 :(得分:1)

string substr ( string $string , int $start [, int $length ] )

http://php.net/manual/en/function.substr.php

答案 6 :(得分:1)

更灵活的方式是具有两个参数的函数:

function lchar($str,$val){return strlen($str)<=$val?$str:substr($str,0,$val).'...';}

用法:

echo lchar($str,200);

答案 7 :(得分:1)

function TitleTextLimit($text,$limit=200){
 if(strlen($text)<=$limit){
    echo $text;
 }else{
    $text = substr($text,0,$limit) . '...';
    echo $text;
 }

答案 8 :(得分:1)

这是最简单的方法

http_response_code

了解更多详情

https://www.w3schools.com/php/func_string_substr.asp

http://php.net/manual/en/function.substr.php

答案 9 :(得分:0)

echo strlen($row['style-info']) > 200) ? substr($row['style-info'], 0, 200)."..." : $row['style-info'];

答案 10 :(得分:0)

echo strlen($row['style-info'])<=200 ? $row['style-info'] : substr($row['style-info'],0,200).'...';

答案 11 :(得分:0)

尝试一下:

echo ((strlen($row['style-info']) > 200) ? substr($row['style-info'],0,200).'...' : $row['style-info']);

答案 12 :(得分:0)

这个对我有用,也很简单

<?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 "..."; 

?>

答案 13 :(得分:0)

在这段代码中,我们定义了一个方法,然后我们可以简单地调用它。我们给它两个参数。第一个是文本,第二个应该是您要显示的字符数。

function the_excerpt(string $text,int $lenth)
{
    if(strlen($text) > $lenth){
        $text = substr($text,0,$lenth);
    }
    echo $text; 
}

答案 14 :(得分:0)

<?php 
    if(strlen($var) > 200){
        echo substr($var,0,200) . " ...";
    }
    else{
        echo $var;
    }
?>