开发者

Limiting the output of PHP's echo to 200 characters

I'm trying to limit my PHP 开发者_StackOverflow社区echo to only 200 characters and then if there are any more replace them with "...".

How could I modify the following statement to allow this?

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


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


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


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


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


It gives out a string of max 200 characters OR 200 normal characters OR 200 characters followed by '...'

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


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

?>


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


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

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


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

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


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


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


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


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


Try This:

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


In this code we define a method and then we can simply call it. we give it two parameters. first one is text and the second one should be count of characters that you wanna display.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜