Question

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 ?

Was it helpful?

Solution

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

OTHER TIPS

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. ._.

$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!
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top