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

Mary-Kate Olsen
Release: 2024-11-08 00:03:02
Original
876 people have browsed it

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

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!

source:php.cn
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!