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

7

5

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?

Euthanasia answered 25/7, 2010 at 18:10 Comment(0)
T
7

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.

Tremaine answered 25/7, 2010 at 18:11 Comment(1)
Hi, not very good at writing the regular expression rule needed to go inside the preg split function. How would that go to match the contents inside the ()?Euthanasia
A
4

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

Antiserum answered 25/7, 2010 at 18:15 Comment(0)
B
3

If you know for a fact that the strings will always be of the form (a) (b) (c), with precisely one space between each pair of parentheses and with no characters at the beginning or end, you can avoid having to use regexp functions:

$myarray = explode(') (', substr($mystring, 1, -1));
Bhili answered 25/7, 2010 at 18:18 Comment(0)
C
1

Try the below code:

<?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 )
Caulis answered 20/9, 2016 at 7:35 Comment(0)
E
0

Perhaps use preg_split with an alternation pattern:

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

Enlarge answered 25/7, 2010 at 18:11 Comment(0)
T
0

You can try preg_split() function.

Tigre answered 25/7, 2010 at 18:11 Comment(0)
S
0

If your delimiters are consistent like that, 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], "()");
Studley answered 25/7, 2010 at 18:21 Comment(1)
Good point! Either way though, the OP can still explode on ") (" and get what he needs.Studley

© 2022 - 2024 — McMap. All rights reserved.