Search code examples
phpstringstrip

How do you cut off text after a certain amount of characters in PHP?


I have two string that i want to limit to lets say the first 25 characters for example. Is there a way to cut off text after the 25th character and add a ... to the end of the string?

So '12345678901234567890abcdefg' would turn into '12345678901234567890abcde...' where 'fg' is cut off.


Solution

  • May I make a modification to pallan's code?

    $truncated = (strlen($string) > 20) ? substr($string, 0, 20) . '...' : $string;
    

    This doesn't add the '...' if it is shorter.