Performs a multi-byte safe substr() operation based on the number of characters. The position is counted from the beginning of str
. The first character’s position is 0. The second character position is 1, and so on.
Syntax:
mb_substr($str,$start,$end,$encoding)
What is mb_substr() function
mb in mb_substr() function stands for multi-byte, when we manipulate the string with the help of inbuilt functions like trim(), split(), splice(), etc strings encoded in a multi-byte, and when we use some special character in the string then functions like substr() does not recognize it and result maybe something like �.
In mb_substr() we have facility to tell the function string encoding. So if any special string does not understand by the substr() function, we can use mb_substr() function to get the desired result for us after mentioning the encoding in the function.
Difference between substr and mb_substr
the difference between substr() and mb_substr() function is in mb_substr() we can define the encoding of the string and in substr() we do not have that option. For example, we need to get some characters from the string then obviously we will use substr() function, but if that string or paragraph contains some special characters then substr() will not recognize those strings, but if we talk about the mb_substr(), as we have the option to define encoding then the function will understand the special characters and output the desired result. You can see the below examples
Example 1
<?php $string = "Hello Atcodex!"; echo "Updated string: " . mb_substr($string, 2, 3) . "\n"; echo substr("hi mémé", 0 , 5); // will print hi m� echo mb_substr("hi mémé", 0 , 5); // will print hi mé ?>
Output:
Updated string: llo
hi m�
hi mé
Example 2
<?php $string = "Hello Atcodex!"; echo "Updated string normal: " . mb_substr($string, 2, 3) . "\n"; echo "<br>"; echo "Updated string with UTF8: " . mb_substr($string, 2, 3,'UTF8') . "\n"; echo "<br>"; echo "Updated string UTF16: " . mb_substr($string, 2, 3,'UTF16') . "\n"; echo "<br>"; echo "Updated string UTF32: " . mb_substr($string, 2, 3,'UTF32') . "\n"; ?>
Output:
Updated string normal: llo
Updated string with UTF8: llo
Updated string UTF16: o Atco
Updated string UTF32: codex!
Conclusion:
We have tried to explain the mb_substr() function with examples. You can check the above code and understand how to use mb_substr() function when you have some special characters in the string and you need to perform some activity in the application on the basis of that particular string.
Note: Use mb_substr() function if you have special characters in the string and paragraph.
Please check How to Remove Last Character from String in PHP