Home  >  Article  >  Backend Development  >  How to Truncate Strings with Respect to Word Boundaries in PHP?

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

Barbara Streisand
Barbara StreisandOriginal
2024-10-24 06:25:30998browse

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:

<code class="php">$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;</code>

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.

The above is the detailed content of How to Truncate Strings with Respect to Word Boundaries in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn