Georgy Georgy - 11 months ago 41
PHP Question

How to use the explode function in PHP using 2 delimeters instead of 1?

Suppose I have the following:

$string = "(a) (b) (c)";

How would I explode it to get the contents inside the parenthesis. If the string's contents were separated by just one symbol instead of 2 I would have used:

$string = "a-b-c";
explode("-", $string);

But how to do this when 2 delimiters are used to encapsulate the items to be exploded?

Answer Source

You have to use preg_split or preg_match instead.


$string = "(a) (b) (c)";
print_r(preg_split('/\\) \\(|\\(|\\)/', $string, -1, PREG_SPLIT_NO_EMPTY));
    [0] => a
    [1] => b
    [2] => c

Notice the order is important.