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?
Related Topics
PHP: Check Strings with Ctype-Functions for Character Classes
Article | 0 Comments
PHP: Remove arbitrary Characters at the Beginning and the End of a String
Tutorial | 0 Comments
JavaScript: Remove last character from string
Tip | 5 Comments
HTML: No line break between particular words
Tip | 0 Comments
What is a non breaking space?
Info | 0 Comments
PHP: Get first Digit of Number or String
Tutorial | 0 Comments
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.
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:
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