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

How Can I Truncate Multibyte Strings While Preserving Word Boundaries in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-14 17:02:18308browse

How Can I Truncate Multibyte Strings While Preserving Word Boundaries in PHP?

Truncating a Multibyte String with Word Boundary Control

When working with multibyte strings, truncating them to a specific character count can be a challenging task, especially when considering word boundaries. One common way to address this is to use the multibyte string functions provided by PHP.

One approach involves utilizing the following steps:

  1. Subtract the length of the terminator string from the desired truncated length.
  2. Determine if the string exceeds the calculated limit.
  3. Identify the last space character within the string within the calculated limit.
  4. Truncate the string either at the last space or at the calculated limit.
  5. Append the terminator string to the truncated portion.

While this approach seems logical, implementing it using str or mb_ functions can be tricky. Alternatively, PHP offers a built-in function that performs multibyte truncation: mb_strimwidth.

<?php
$string = "Answer to the Ultimate Question of Life, the Universe, and Everything";
$maxLength = 50;
$terminator = ' …';
$truncatedString = mb_strimwidth($string, 0, $maxLength - strlen($terminator), $terminator);

echo $truncatedString; // Output: "Answer to the Ultimate Question of Life, the …"
?>

While mb_strimwidth does not consider word boundaries, it provides a reliable and straightforward method for truncating multibyte strings.

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