Preserving Words with PHP's substr Function
When using the substr function, it's common to encounter situations where the resulting string ends abruptly in the middle of a word. If you want to ensure that the truncated string ends at a word boundary, consider implementing the following solution:
Solution:
To achieve the desired behavior, you can leverage the strpos function, which finds the position of the first occurrence of a specified string within a larger string. In this case, we utilize the space character (" ") as our marker for word boundaries.
Code:
substr($body, 0, strpos($body, ' ', 260))
Explanation:
This code:
Usage:
Replace the existing substr call:
echo substr("$body",0,260);
with the modified code:
echo substr($body, 0, strpos($body, ' ', 260));
By implementing this solution, you can ensure that substr produces strings that respect word boundaries, preventing abrupt truncations in the middle of words.
The above is the detailed content of How to Ensure Substr Function Doesn't Cut Words in Half?. For more information, please follow other related articles on the PHP Chinese website!