Home  >  Article  >  Backend Development  >  How to Maintain Word Boundaries When Truncating Strings?

How to Maintain Word Boundaries When Truncating Strings?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-24 06:32:02920browse

How to Maintain Word Boundaries When Truncating Strings?

Maintaining Word Boundaries When Truncating Strings

In a previous query, a user sought to truncate a string to 100 characters using the substr() function. However, this method simply took the first 100 characters, potentially breaking words in the process.

Problem Statement

The objective is to truncate a string to a maximum of 100 characters while ensuring that words remain intact. For example:

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

$small = truncate_string($big);

echo $small;

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

PHP Solution

The following code provides a solution:

<code class="php">function truncate_string($string)
{
    $pos = strpos($string, ' ', 200);
    return substr($string, 0, $pos);
}</code>

Explanation:

  • The strpos() function searches for the next space character in the string within the first 200 characters. This ensures we don't truncate past the first 100 characters.
  • The substr() function returns the substring from the beginning of the string to the specified position, which is the position of the first space within the first 200 characters.

The above is the detailed content of How to Maintain Word Boundaries When Truncating Strings?. 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