"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Truncate Strings with Respect to Word Boundaries in PHP?

How to Truncate Strings with Respect to Word Boundaries in PHP?

Published on 2024-11-07
Browse:798

How to Truncate Strings with Respect to Word Boundaries in PHP?

Shortening Strings with Respect to Word Boundaries in PHP

In PHP, the substr() function provides a convenient way to truncate strings. However, by default, it does not consider word boundaries, which can result in incomplete or awkward excerpts.

To address this issue, we can modify our approach to prioritize preserving whole words. Consider the following snippet:

$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!";

$pos = strpos($big, ' ', 100); // Find the first space within the first 100 characters
$small = substr($big, 0, $pos); // Truncate at the space to keep the word intact

echo $small;

Here, we first search for the position of the space within the first 100 characters of the string (strpos($big, ' ', 100)). We then use this position as the cutoff point for truncation (substr($big, 0, $pos)).

This approach ensures that we always extract a complete word, even if the full string exceeds 100 characters. In this example, the output will be:

This is a sentence that has more than 100 characters in it, and I want to return a string of only

This solution effectively preserves word boundaries while respecting the 100-character limit.

Release Statement This article is reprinted at: 1729721417 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3