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

问题描述 投票:10回答:13

我试图将我的PHP echo限制为只有200个字符然后如果有更多用"..."替换它们。

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

<?php echo $row['style-info'] ?>
php
13个回答
54
投票

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

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); ?>

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

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

0
投票

试试这个:

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

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

?>

17
投票

像这样:

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

或包裹在一个功能:

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

echo_200($str);

7
投票

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

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

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


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

3
投票

它给出一个最多200个字符的字符串或200个普通字符或200个字符后跟'...'

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

1
投票
string substr ( string $string , int $start [, int $length ] )

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


1
投票

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

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

用法:

echo lchar($str,200);

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

1
投票

这是最简单的方法

//substr(string,start,length)
substr("Hello Word", 0, 5);
substr($text, 0, 5);
substr($row['style-info'], 0, 5);

了解更多细节

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

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

© www.soinside.com 2019 - 2024. All rights reserved.