There are several ways to split a string by its length in php. In this article, we will see some of the common and easy ways to do that.

How to split a string using str_split()

By using the str_split() we can easily split the string by its length in PHP. Using the str_split() we can split a string into an array of substrings of a specified length.

Following is the example:

$string = "Hello World";
$chunks = str_split($string, 2);
print_r($chunks);

In the above example, we use the str_split() function to split the string into an array of substrings, each of length 2. The resulting array will contain [“He”, “ll”, “o “, “Wo”, “rl”, “d”].

How to split string using preg_split()

Using the preg_split() with the regular expressions we can split the string by its length. This approach involves defining a regular expression that matches substrings of a specified length and the string will be split by using the preg_split() function.

Following is an example of how to split the string using preg_split()

$string = "Hello World";
$length = 4;
$regex = "/.{1,$length}/";
$chunks = preg_split($regex, $string, -1, PREG_SPLIT_NO_EMPTY);

print_r($chunks);

In the above example, we define the string with “Hello World” and the split length as 4. Using the following regular expression "/.{1,$length}/" we match any character repeated 1 to 4 times and then use the preg_split() function to split the string. By using the PREG_SPLIT_NO_EMPTY exclude any empty substrings from the resulting array using the flag.

The resulting array will contain [“Hell”, “o Wo”, “rld”].

Categorized in:

Tagged in: