Home  >  Article  >  Backend Development  >  How to Truncate Strings While Preserving Word Integrity in PHP?

How to Truncate Strings While Preserving Word Integrity in PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-10-24 06:24:30559browse

How to Truncate Strings While Preserving Word Integrity in PHP?

Preserving Word Integrity When Truncating Strings

In a previous inquiry, you expressed a need to shorten strings to 100 characters while maintaining the integrity of words. The initial approach using substr() blindly cut off at the 100th character.

To achieve your desired result, consider the following PHP code:

<code class="php">$pos = strpos($content, ' ', 200);
substr($content, 0, $pos);</code>

This code:

  1. Uses strpos() to find the position of the first space character within the first 200 characters of the string. This step is used to identify the end of the last complete word within the first 100 characters.
  2. The resulting position is then used in substr() to extract the substring from the beginning of the string up to but not including the space character. This ensures that the truncated string doesn't break any words and stays within the limit of 100 characters.

The above is the detailed content of How to Truncate Strings While Preserving Word Integrity 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