Using PHP str_split to Split Strings into Character Arrays
This article explains how to use PHP's str_split function to divide a string into an array of characters, covering basic syntax, specifying element length, handling multibyte characters, and providing practical code examples with output demonstrations.
In PHP, when you need to split a string into a character array, you can easily achieve this using the PHP function str_split . This article introduces how to use str_split and provides several usage examples.
The basic syntax of the str_split function is:
array str_split ( string $string [, int $split_length = 1 ] )Here, $string is the string to be split, and the optional $split_length parameter specifies the length of each element, defaulting to 1.
Now let's look at a few examples.
Example 1: Basic Usage
$string = "Hello, World!";
$arr = str_split($string);
print_r($arr);Output:
Array
(
[0] => H
[1] => e
[2] => l
[3] => l
[4] => o
[5] => ,
[6] =>
[7] => W
[8] => o
[9] => r
[10] => l
[11] => d
[12] => !
)In this example, the string "Hello, World!" is split into a character array and printed with print_r , showing each character as an array element.
Example 2: Specifying Element Length
$string = "PHP is awesome!";
$arr = str_split($string, 3);
print_r($arr);Output:
Array
(
[0] => PHP
[1] => is
[2] => aw
[3] => es
[4] => om
[5] => e!
)Here the $split_length parameter is set to 3, so the original string is divided into elements each containing three characters.
Example 3: Handling Multibyte Characters
// Using a UTF‑8 encoded string
$string = "你好,世界!";
$arr = str_split($string, 3);
print_r($arr);Output:
Array
(
[0] => 你好,
[1] => 世界!
)This example processes a UTF‑8 string with $split_length set to 3. Although each Chinese character occupies three bytes, str_split correctly splits the string into character elements.
Note that when a string contains multibyte characters, str_split may split characters incorrectly (e.g., Chinese characters into separate parts). In such cases, you can use alternatives like mb_str_split or preg_split to handle the splitting properly.
Summary
This article introduced the basic usage of the PHP function str_split for splitting strings into character arrays, demonstrated how to specify element length, and showed handling of multibyte characters. It also highlighted the need for alternative functions when dealing with multibyte strings.
PHP Practical
Scan the QR code to receive free learning materials
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.