5

I want list some items in the list but upto some few characters, if the characters limit reaches then just show ....

I have this echo(substr($sentence,0,29)); but how put it condition ?

Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
SagarPPanchal
  • 9,839
  • 6
  • 34
  • 62

3 Answers3

10

Use mb_strlen() and an if

$allowedlimit = 29;
if(mb_strlen($sentence)>$allowedlimit)
{
    echo mb_substr($sentence,0,$allowedlimit)."....";
}

or in a simpler way... (using ternary operator)

$allowedlimit = 29;
echo (mb_strlen($sentence)>$allowedlimit) ? mb_substr($sentence,0,$allowedlimit)."...." : $sentence;

in a function:

function app_shortString($string, $limit = 32) {
     return (mb_strlen($string)>$limit) ? mb_substr($string,0,$limit)." ..." : $string;
}
Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
  • Why *mb_* instead of just `strlen`? (You can use [mb overloading](http://www.php.net/manual/en/mbstring.overload.php), of course.) – kojiro Apr 25 '14 at 11:42
  • @ShankarDamodaran So the choice is between `mb_string`, which is an external dependency, or `substr`, which doesn't support multibyte characters, but is built in every default install. – kojiro Apr 25 '14 at 11:48
  • 1
    @ShankarDamodaran Actually, the manual only says it's unstable in per-directory context. Presumably that means `` context in apache configs. It should be as stable as anything else in regular php.ini. – kojiro Apr 25 '14 at 11:50
3

This should do it:

if(strlen($sentence) >= 30) {
    echo substr($sentence,0,29)."...";
} else {
    echo $sentence;
}

More infos about strlen(): http://www.php.net/manual/de/function.strlen.php

Edit/ Crap, wrong function in mind, sry. ._.

Realitätsverlust
  • 3,941
  • 2
  • 22
  • 46
1
$text = 'this is a long string that is over 28 characters long';

strlen($text) > 28 ? substr($text, 0, 28) .'...' : $text;

gives: this is a long string that i...


$text = 'this is a short string!';

echo strlen($text) > 28 ? substr($text, 0, 28) .'...' : $text;

gives: this is a short string!
Ryan Vincent
  • 4,483
  • 7
  • 22
  • 31