Home >Backend Development >PHP Tutorial >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:
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!