Home >Backend Development >PHP Tutorial >How to Maintain Word Boundaries When Truncating Strings?
Maintaining Word Boundaries When Truncating Strings
In a previous query, a user sought to truncate a string to 100 characters using the substr() function. However, this method simply took the first 100 characters, potentially breaking words in the process.
Problem Statement
The objective is to truncate a string to a maximum of 100 characters while ensuring that words remain intact. For example:
$big = "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!" $small = truncate_string($big); echo $small; // OUTPUT: "This is a sentence that has more than 100 characters in it, and I want to return a string of only"
PHP Solution
The following code provides a solution:
<code class="php">function truncate_string($string) { $pos = strpos($string, ' ', 200); return substr($string, 0, $pos); }</code>
Explanation:
The above is the detailed content of How to Maintain Word Boundaries When Truncating Strings?. For more information, please follow other related articles on the PHP Chinese website!