PHP String Split

There are a few functions that can be used to split a string in PHP. Each of them is designed for different situations.

  • explode()

    Split a string into an array by a delimiter string.

  • strtok()

    Split a string into smaller strings by any character from a delimiter. It returns a string for each call.

  • str_split()

    Split a string into an array by length. The result will be an array containing chunks with each being in the specified length. The default length is 1.

  • preg_split()

    Split a string into an array by a regular expression.

explode()

explode() splits a string into an array by a string. It also accept an optional $limit argument. So you can control the maximum count of the split components.

Syntax

explode ( string $delimiter , string $string [, int $limit = PHP_INT_MAX ] ) : array

Examples

$a = "apple banana cherry";

// No limit is specified, it returns all the components.
$data = explode( " ", $a );     // $data: ["apple", "banana", "cherry"]

// Specify a positive limit, the string is splited into $limit components.
// Note the last components are merged into one component.
$data = explode( " ", $a, 2 ) ; // $data: ["apple", "banana cherry"]

// Specify zero as limit, it will be treated as 1
$data = explode( " ", $a, 0 );   // $data: ["apple banana cherry"]

// Specifiy a negative limit, the last abs($limit) components will be excluded.
$data = explode( " ", $a, -2 );  // $data: ["apple"]

Note that if the delimiter is located at the end the string, there will an empty component in the end of the result array. And if multiple delimiters are located together, there will be some empty components.

// Delimiter is located in the end.

$b = "apple banana cherry ";
$data = explode( " ", $str );     // $data: ["apple", "banana", "cherry", ""]

// Multiple continuous delimiters.

$c = "apple,,banana,cherry";
$data = explode( ",", $str );     // $data: ["apple", "", "banana", "cherry"]

If that is not what you want, you may exclude the empty values by yourself or just use strtok() or preg_split() instead.

Note: explode() is binary-safe.

strtok()

strtok() can use multiple one-character delimiters to split a string. That means any character from $token will be treated as a delimiter.

Different from other split functions, explode() returns a string for each call. And only the first call uses the string argument, as it keeps track of where it is in the current string. The subsequent calls does not need the parameter. Thereby there are two forms of syntax for this function.

Syntax

strtok ( string $str , string $token ) : string

strtok ( string $token ) : string

Note:

explode() may return false if there are no component to return. And remember use === to check whether it return a boolean false, for there are string values will be treated evaluated to false, such as "".

Examples

function str_to_tokens( $str, $token = ",n" ) {
    $data = array();

    $tok = strtok( $str, $token );    
    while( $tok !== false ) {
        $data[] = $tok;
        $tok = strtok( $token ); // Note, $str is not needed anymore here.
    }

    return $data;
}

$a = "applenbanana,cherry";
$data = str_to_tokens( $a ); // $data: ["apple", "banana", "cherry"]

// Continous delimiters
$b = "applennbanana,cherryn";
$data = str_to_tokens( $b ); // $data: ["apple", "banana", "cherry"]

In above examples, you may notice that strtok() won”t produce empty tokens if there are continuous delimiters or the the delimiter is located in the end in the string.

str_split()

str_plit() splits a string into an array by length. The default length is 1 if it is not specified.

Syntax

str_split ( string $string [, int $split_length = 1 ] ) : array

Examples

$str = "abcdefghig";
$data = str_split( $str ); // $data: ["a", "b", "c", " ", "d", "e"]
$data = str_split( $str, 2 ); // $data: ["ab", "c ", "de"]

Note:

str_split() will split into bytes, rather than characters when dealing with a multi-byte encoded string.

preg_split()

preg_split() splits a string into an array by a regular expression. You can use this function to do complex split operations.

Note:

If you don’t need the power of regular expressions, you can choose faster (albeit simpler) alternatives like explode(), strtok() or str_plit().

Syntax

preg_split ( string $pattern , string $subject [, int $limit = -1 [, int $flags = 0 ]] ) : array

If the argument limit is set, only substrings up to $limit are returned with the rest of the string being placed in the last string. -1 and 0 means “no limit”, and, as is standard across PHP, you can use NULL to skip to the flags parameter.

The argument flags can be any combination of the following flags ( use / to combine flags)

  • PREG_SPLIT_NO_EMPTY

    Only non-empty pieces will be returned.

  • PREG_SPLIT_DELIM_CAPTURE

    Parenthesized expression in the delimiter pattern will be captured and returned as well.

  • PREG_SPLIT_OFFSET_CAPTURE

    For every occurring match the appendant string offset will also be returned. Note that this changes the return value in an array where every element is an array consisting of the matched string at offset 0 and its string offset into subjectat offset 1.

Note:

preg_split() returns false if on failure,such as the pattern is not valid.

Examples

$str = "apple banada, cherry ";

// Delimiter is a character that can be " ", "t", "r", "n" or "f".
$data = preg_split( "|[s,]|", $a ); // $data:  ["apple", "banada", " ", "cherry", " "]

// Delimiter is any number of characters which includes " ",
// "t", "r", "n" or "f".

$data = preg_split( "|[s,]+|", $a ); // $data:  ["apple", "banada", "cherry", " "]

// Use flag PREG_SPLIT_NO_EMPTY to exclude empty parts
$data = preg_split( "|[s,]+|", $a, null, PREG_SPLIT_NO_EMPTY );
// $data:  ["apple", "banada", "cherry"]

// Limit the count of returned substrings.
$data = preg_split( "|[s,]+|", $a, 2 ); // $data:  ["apple", "banada, cherry "]
$data = preg_split( "|[s,]+|", $a, 3 ); // $data:  ["apple", "banada", "cherry "]

// Delimiter does not match any part in the string.
$data = preg_split( "|-_|", $a ); // $data:  ["apple  banada, cherry "]

// Pattern is not valid, it reutrn false, and a PHP warning may be generated.
$data = preg_split( "|-", $a );  // $data is false

Split string to array excluding empty values

As you see, passing PREG_SPLIT_NO_EMPTY flag to preg_split() will get an array in which empty values are excluded. If you do not need the power of regular expressions, use below one.

function str_to_tokens( $str, $token ) {
    $data = array();

    $tok = strtok( $str, $token );    
    while( $tok !== false ) {
        $data[] = $tok;
        $tok = strtok( $token );
    }

    return $data;
}

$str = "applennbanana,cherryn";
$data = str_to_tokens( $str ); // $data: ["apple", "banana", "cherry"]