Current Location: Home> Latest Articles> How to Use the mb_str_split Function to Split Multibyte Strings: Step-by-Step Guide with Examples

How to Use the mb_str_split Function to Split Multibyte Strings: Step-by-Step Guide with Examples

gitbox 2025-09-19
<span><span><span class="hljs-meta">&lt;?php</span></span><span>
</span><span><span class="hljs-comment">// This is a PHP code example unrelated to the article content</span></span><span>
</span><span><span class="hljs-keyword">echo</span></span><span> </span><span><span class="hljs-string">"Welcome to the PHP Multibyte String Splitting Tutorial!"</span></span><span>;
</span><span><span class="hljs-meta">?&gt;</span></span><span>
<p><hr></p>
<p></span><?php<br>
/*<br>
Article Title: How to Use the mb_str_split Function to Split Multibyte Strings: Step-by-Step Guide with Examples<br>
*/</p>
<p>// When working with multibyte strings in PHP, standard string functions may not correctly recognize characters such as Chinese, Japanese, or Korean.<br>
// Starting from PHP 7.4, the mb_str_split function is available, specifically designed to split multibyte strings into individual characters or substrings of a given length.</p>
<p>// 1. Basic Usage<br>
$string = "你好,世界!";<br>
$chars = mb_str_split($string);<br>
echo "Basic split result:\n";<br>
print_r($chars);</p>
<p>// Output:<br>
// Array<br>
// (<br>
//     [0] => 你<br>
//     [1] => 好<br>
//     [2] => ,<br>
//     [3] => 世<br>
//     [4] => 界<br>
//     [5] => !<br>
// )</p>
<p>// 2. Splitting with a Specified Length<br>
// You can specify the length of each substring using the second parameter<br>
$parts = mb_str_split($string, 2);<br>
echo "Split every two characters:\n";<br>
print_r($parts);</p>
<p>// Output:<br>
// Array<br>
// (<br>
//     [0] => 你好<br>
//     [1] => ,世<br>
//     [2] => 界!<br>
// )</p>
<p>// 3. Setting the Character Encoding<br>
// By default, mb_str_split uses the internal character encoding (usually UTF-8), but you can also specify the encoding<br>
$charsUtf8 = mb_str_split($string, 1, "UTF-8");<br>
echo "UTF-8 split result:\n";<br>
print_r($charsUtf8);</p>
<p>// 4. Example Use Cases<br>
// - Process multibyte user input character by character, e.g., emoji filtering or sensitive word checks<br>
// - Display split strings one by one in the interface<br>
// - Count and split multibyte string lengths</p>
<p>// Example: Counting string length<br>
$length = count(mb_str_split($string));<br>
echo "The string length is: " . $length . " characters\n";</p>
<p data-is-last-node="" data-is-only-node="">// Summary:<br>
// mb_str_split is an efficient tool for handling multibyte strings, helping to avoid garbled text issues that may occur with traditional functions.<br>
// Simply pass in the string, set the desired substring length and encoding, and you can easily complete the splitting task.<br>
?><br>
</span>