33 Votes

PHP: Cut off String at last Space

Question by Compi | Last update on 2022-04-25 | Created on 2016-06-06

I would like to display a preview of some texts on a website. For that, I am reading out the first 200 characters from my database in order to show this string.

Now, often, it happens that this string just ends somewhere in the middle of a word what is looking quite ugly. I would rather have the text end at the end of a word. So, I would like to use PHP for searching the last blank space character in the string to shorten the text at this point.

Does someone know any PHP function for that?

ReplyPositiveNegative
3Best Answer3 Votes

You can just use the PHP function strrpos for that. This function is providing the last occurrence of a string in a given string. 

With cutting off at this position, your code could look like that:

$s = strip_tags($s);       // remove HTML
$p = strrpos($s, ' ');     // search for last space

if ($p !== false) {        // space was found
  $s = substr($s, 0, $p);  // cut off
}

The first line is optional, but helpful. If your string $s is containing some HTML tags, it is possible that the string is cut off just before one of the ending tags. This can lead to strange effects (for example that starting with the text the rest of the web page becomes a link or bold).

After that, we are searching for the last space occurrence and we will only trim the string if we have found a blank character.
Last update on 2022-04-25 | Created on 2016-06-06

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.