0 0 Votes

PHP: Cut off String at last Space

Question by Compi | 06/06/2016 at 16:24

I would like to display a preview of some text 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?



Show Profile | Message
0Best Answer
0 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.
06/06/2016 at 17:44

ReplyPositive Negative

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.


Ask your own question or write your own articles on askingbox.com. How to do.