How to split a string using multiple delimiters in PHP?

Split a string using preg_split

The preg_split function can split a string using regular expression. I demonstrate this in the below example:

<?php
$foo = "this/is\a-test_to-split=a-string-using?multiple_delimiters";
$res = preg_split("/(\/|\\\|-|_|\?|=)/", $foo);
print_r($res);
?>

Result:

Array
(
    [0] => this
    [1] => is
    [2] => a
    [3] => test
    [4] => to
    [5] => split
    [6] => a
    [7] => string
    [8] => using
    [9] => multiple
    [10] => delimiters
)

In the above example, the string is split along the /, \, -, _, and = delimiters.

Split a string using explode along with str_replace

Another solution is to choose a single delimiter and replace all the other delimiters with the chosen one. After that, the explode function can be used. I demonstrate this in the below example:

<?php

$foo = "this/is\a-test_to-split=a-string-using?multiple_delimiters";
$res=explode('\\',str_replace(array('/','-','_','?','='),'\\',$foo));
print_r($res);

?>

Result:

Array
(
    [0] => this
    [1] => is
    [2] => a
    [3] => test
    [4] => to
    [5] => split
    [6] => a
    [7] => string
    [8] => using
    [9] => multiple
    [10] => delimiters
)

In the above example, all the delimiters are replaced with \\, and then the same delimiter is used to split the string.

Leave a Reply