Home >Backend Development >PHP Tutorial >How to Make PHP's substr Function Break Strings at Word Boundaries?

How to Make PHP's substr Function Break Strings at Word Boundaries?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-08 00:03:02940browse

How to Make PHP's substr Function Break Strings at Word Boundaries?

Ensuring PHP substr Breaks Strings at Word Boundaries

When truncating strings using the substr function, it's important to ensure that the cutoff occurs at the end of a word, not in the middle of one. This is crucial for maintaining readability and conveying the intended meaning in text output.

To achieve this, you can utilize the following code:

substr($body, 0, strpos($body, ' ', 260))

In this snippet:

  • substr() takes the string $body and selects a substring with the starting position 0.
  • strpos() searches for the first occurrence of the space character (' ') within $body starting from position 260.
  • The result of strpos() specifies the position where the substring should end, ensuring that the cutoff occurs at the first word boundary after 260 characters.

The above is the detailed content of How to Make PHP's substr Function Break Strings at Word Boundaries?. 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