Home > Backend Development > PHP Tutorial > How Can I Truncate a Multibyte String While Preserving Word Boundaries?

How Can I Truncate a Multibyte String While Preserving Word Boundaries?

Mary-Kate Olsen
Release: 2024-12-18 02:58:10
Original
132 people have browsed it

How Can I Truncate a Multibyte String While Preserving Word Boundaries?

Multibyte String Truncation with Word Boundary Control

Question:

How can I truncate a multibyte string to a specified number of characters, maintaining word boundaries?

Steps for Truncation:

  1. Calculate the maximum truncation length by subtracting the length of the terminator string from the desired character count.
  2. Check if the string is longer than the maximum length; if not, return the unchanged string.
  3. Find the last space character within the calculated truncation length.
  4. Truncate the string at the last space character or the calculated length if no space is found.
  5. Append the terminator string to the truncated string.
  6. Return the modified string.

Implementation (Using mb_strimwidth for Multibyte Character Support):

function truncate_with_words($string, $chars = 50, $terminator = '...') {}
Copy after login

[Implementation]

The above is the detailed content of How Can I Truncate a Multibyte String While Preserving 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