How to Truncate Text to 100 Characters while Respecting Full Words?

DDD
Release: 2024-10-24 06:37:02
Original
161 people have browsed it

How to Truncate Text to 100 Characters while Respecting Full Words?

Respecting Full Words in Text Truncation

In this scenario, you seek to truncate a string to 100 characters while preserving full words. Unlike the straightforward approach of using substr, this method aims to prevent word segmentation.

To achieve this, consider the following approach:

<code class="php">$content = "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($content, ' ', 100);
$truncated = substr($content, 0, $pos);</code>
Copy after login

In this code, we first locate the first space after the 100th character using strpos. This ensures that we do not break a word. Subsequently, we use substr to truncate the string up to that position, respecting word boundaries.

The output would 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

The above is the detailed content of How to Truncate Text to 100 Characters while Respecting Full Words?. 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
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!