I\'m looking for a way to limit a string in php and add on ... at the end if the string was too long.
$value = str_limit('This string is really really long.', 7);
// This st...
2nd argument is where to start string and 3rd argument how many characters you need to show
$title = "This is for testing string for get limit of string This is for testing string for get limit of string This is for testing string for get limit of string This is for testing string for get limit of string";
echo substr($title,0,50);
To truncate a string provided by the maximum limit without breaking a word use this:
/**
* truncate a string provided by the maximum limit without breaking a word
* @param string $str
* @param integer $maxlen
* @return string
*/
public static function truncateStringWords($str, $maxlen): string
{
if (strlen($str) <= $maxlen) return $str;
$newstr = substr($str, 0, $maxlen);
if (substr($newstr, -1, 1) != ' ') $newstr = substr($newstr, 0, strrpos($newstr, " "));
return $newstr;
}
In another way to limit a string in php and add on readmore text or like '...' using below code
if (strlen(preg_replace('#^https?://#', '', $string)) > 30) {
echo substr(preg_replace('#^https?://#', '', $string), 0, 35).'…';
}