How to use break function in PHP using 2 meters instead of 1?

Suppose I have the following:

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

How would I explode to get the contents inside the parenthesis. If the contents of the string were separated by only one character instead of 2, I would use:

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

But how to do it when 2 separators are used to encapsulate items that need to be exploded?

+5
source share
7 answers

You should use preg_splitor preg_matchinstead.

Example:

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

Please note that order is important.

+6
source

If there are no nesting brackets, you can use a 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"
}

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

+4

, (a) (b) (c), , regexp:

$myarray = explode(') (', substr($mystring, 1, -1));
+3

Try the code below:

<?php
  $s="Welcome to (London) hello ";    
  $data = explode('(' , $s );    
  $d=explode(')',$data[1]);    
  print_r($data);    
  print_r($d);    
?>        

Output:

Array ( [0] => Welcome to [1] => London) hello )
Array ( [0] => London [1] => hello )
+1
source

Perhaps use preg_split with an interleave pattern:

http://www.php.net/manual/en/function.preg-split.php

0
source

You can try it preg_split().

0
source

If your delimiters are consistent, then you can do this

$string = "(a) (b) (c)";
$arr = explode(") (", $string);
// Then simply trim remaining parentheses off.
$arr[0] = trim($arr[0], "()");
end($arr) = trim($arr[0], "()");
0
source

All Articles