Home > Article > Backend Development > How to Truncate Text to 100 Characters while Respecting Full Words?
Respecting Full Words in Text Truncation
In this scenario, you seek to truncate a string to 100 characters while preserving full words. Unlike the straightforward approach of using substr, this method aims to prevent word segmentation.
To achieve this, consider the following approach:
<code class="php">$content = "This is a sentence that has more than 100 characters in it, and I want to return a string of only full words that is no more than 100 characters!"; $pos = strpos($content, ' ', 100); $truncated = substr($content, 0, $pos);</code>
In this code, we first locate the first space after the 100th character using strpos. This ensures that we do not break a word. Subsequently, we use substr to truncate the string up to that position, respecting word boundaries.
The output would be:
"This is a sentence that has more than 100 characters in it, and I want to return a string of only"
The above is the detailed content of How to Truncate Text to 100 Characters while Respecting Full Words?. For more information, please follow other related articles on the PHP Chinese website!