Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP – mb_strimwidth (multybyte strimwidth) function
The mb_strimwidth() function in PHP is used to truncate a multibyte string to a specified width. This function is particularly useful for handling text in different character encodings while maintaining proper string length control.
Syntax
string mb_strimwidth($str, $start, $width, $trimmarker, $encoding)
Parameters
mb_strimwidth() accepts five parameters to control string truncation −
$str − The input string to be truncated.
$start − Starting position for truncation (0-based index).
$width − Maximum width of the truncated string. Negative values count from the end.
$trimmarker − String appended when truncation occurs (optional).
$encoding − Character encoding. Uses internal encoding if omitted (optional).
Return Value
Returns the truncated string. If a trim marker is specified, it replaces the last characters to fit within the specified width.
Examples
Basic Usage
<?php
// Set UTF-8 encoding
mb_internal_encoding("UTF-8");
// Truncate string starting from position 2, width of 15
$result = mb_strimwidth("Simply Easy Learning!", 2, 15, "...");
echo $result;
?>
mply Easy Le...
Different Starting Positions
<?php $text = "PHP Programming Tutorial"; // Start from beginning echo mb_strimwidth($text, 0, 10, "...") . "<br>"; // Start from position 4 echo mb_strimwidth($text, 4, 10, "...") . "<br>"; // No trim marker echo mb_strimwidth($text, 0, 12); ?>
PHP Prog... Program... PHP Programm
Handling Multibyte Characters
<?php // Japanese text example $japanese = "???????"; // Truncate multibyte string $truncated = mb_strimwidth($japanese, 0, 6, "?", "UTF-8"); echo $truncated; ?>
????
Conclusion
The mb_strimwidth() function provides reliable multibyte string truncation with customizable starting positions and trim markers. It's essential for properly handling international text while maintaining consistent display widths.
