How to use preg_split() Function In PHP

The preg_split() function is used to convert the given string into an array. The function splits the string into smaller strings or sub-strings of length which is specified by the user.

Syntax:

array preg_split( $pattern, $subject, $limit, $flag )

Example:

PHP
<?php 

$str1 = "Geeks"; 
print_r(preg_split('//', $str1 , -1, PREG_SPLIT_NO_EMPTY));

$str2 = "Welcome GfG"; 
print_r(preg_split('//', $str2 , -1, PREG_SPLIT_NO_EMPTY));

?> 

Output
Array
(
    [0] => G
    [1] => e
    [2] => e
    [3] => k
    [4] => s
)
Array
(
    [0] => W
    [1] => e
    [2] => l
    [3] => c
    [4] => o
    [5] => m
    [6] => e
    [7] =>  
    [8] => G
...

Convert a String into an Array of Characters in PHP

Given a string, the task is to convert the string into an array of characters using PHP.

Examples:

Input: str = "GFG" 
Output: Array(
        [0] => G
        [1] => f
        [2] => G
)
Input: str = "Hello Geeks"
Output: Array(
        [0] => H
        [1] => e
        [2] => l
        [3] => l
        [4] => o
        [5] => 
        [6] => G
        [7] => e
        [8] => e
        [9] => k
        [10] => s
)

There are two methods to convert strings to an array of characters, these are:

Table of Content

  • Using str_split() Function
  • Using preg_split() Function
  • Using mb_str_split() Function

Similar Reads

Using str_split() Function

The str_split() function is used to convert the given string into an array. This function basically splits the given string into smaller strings of length specified by the user and stores them in an array and returns the array....

Using preg_split() Function

The preg_split() function is used to convert the given string into an array. The function splits the string into smaller strings or sub-strings of length which is specified by the user....

Using mb_str_split() Function

The mb_str_split() function is used to convert a multibyte string to an array of characters. This function is useful for handling multibyte encodings such as UTF-8....