Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if string exceeds limited characters then show '...'

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 ?

like image 351
SagarPPanchal Avatar asked Apr 25 '14 11:04

SagarPPanchal


2 Answers

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;
}
like image 195
Shankar Narayana Damodaran Avatar answered Nov 17 '22 08:11

Shankar Narayana Damodaran


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

like image 3
Realitätsverlust Avatar answered Nov 17 '22 07:11

Realitätsverlust