Ensure PHP substr Function Ends at Words, Not Characters
The PHP substr() function is a powerful tool for excerpting substrings from a given string. However, it can be frustrating when the excerpt ends in the middle of a word. To resolve this, we can employ regular expressions to find the nearest word boundary to ensure the excerpt ends at a natural word break.
Solution Using Regular Expressions:
The following code snippet demonstrates how to modify the original substr() call to achieve this behavior:
substr($body, 0, strpos($body, ' ', 260))
Explanation:
Example:
Consider the following string:
$body = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
Using the modified substr() call, we can extract a portion of the string that ends at a word boundary:
$excerpt = substr($body, 0, strpos($body, ' ', 260));
Output:
"Lorem ipsum dolor sit amet"
As you can see, the excerpt ends at the nearest word boundary, providing a more natural and complete result.
The above is the detailed content of How to Ensure PHP substr Function Ends at Words, Not Characters?. For more information, please follow other related articles on the PHP Chinese website!