Check if the string exceeds the restricted characters, then show '...'

I want to list some elements in the list, but up to a few characters, if the character limit reaches, then just show ....

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

+4
source share
3 answers

Use mb_strlen()andif

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

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

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

This should do it:

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

Additional information on strlen(): http://www.php.net/manual/de/function.strlen.php

/, , sry.._.

+3
$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!
+1

Source: https://habr.com/ru/post/1538054/


All Articles