0

change large text "Hereisthelargetextbreakwithphp" to "Hereisthelarge..."

$string = "Hereisthelargetextbreakwithphp";
$string = strip_tags($string);
if (strlen($string) > 21) {
    $stringCut = substr($string, 0, 21);
    echo $string = substr($stringCut, 0, strrpos($stringCut, ' ')).'... '; 
}else{
    echo $string;
}

but its nor working for it replace whole this text to "..."

user3176663
  • 107
  • 1
  • 3
  • 11

4 Answers4

0

When there is no space, strrpos returns false which cast to zero in substr function. That results in that substr return empty string

if (strlen($string) > 21) {
    $stringCut = substr($string, 0, 21);
    // If threre is no space in string take it all
    $i = (($i = strrpos($stringCut, ' ')) === false)  ? strlen($stringCut) : $i;
    echo $string = substr($stringCut, 0, $i).'... '; 
}
splash58
  • 26,043
  • 3
  • 22
  • 34
0

Try this:

 $string = strip_tags("Hereisthelargetextbreakwithphp");
 echo (strlen($string) > 14) ? substr($string, 0, 14).'... ' : $string; 
Sankar V
  • 4,110
  • 5
  • 28
  • 52
0
$string = "Hereisthelargetextbreakwithphp";
echo $string = (strlen($string) > 21) ? (substr($string, 0, 21)."....") : $string;

I have used ternary operator you can read more about ternary operator at https://www.abeautifulsite.net/how-to-use-the-php-ternary-operator

Passionate Coder
  • 7,154
  • 2
  • 19
  • 44
0

No need to make custom function, as you are using Codeigniter, you can use text helper directly,

Load the helper first,

$this->load->helper('text');

Then use character_limiter function which is already built in,

$string = character_limiter($stringCut, 21);

And if you want to add ... after string,

$string = character_limiter($stringCut, 21) . '...';

Reference: Codeigniter Text Helper

viral
  • 3,724
  • 1
  • 18
  • 32