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

Barbara Streisand
Release: 2024-10-24 06:25:30
Original
997 people have browsed it

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>
Copy after login

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
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!