Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

explode

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?

like image 898
Georgy Avatar asked Jul 25 '10 18:07

Georgy


2 Answers

You have to use preg_split or preg_match instead.

Example:

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

Notice the order is important.

like image 123
Artefacto Avatar answered Nov 05 '22 21:11

Artefacto


If there is no nesting parenthesis, you can use regular expression.

$string = "(a) (b) (c)";
$res = 0;
preg_match_all("/\\(([^)]*)\\)/", $string, $res);
var_dump($res[1]);

Result:

array(3) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
}

See http://www.ideone.com/70ZlQ

like image 21
kennytm Avatar answered Nov 05 '22 19:11

kennytm