0

I am trying to explode() with multiple delimiters.

With the delimiters:

  • "&"
  • " and "
  • "/"
  • ","

So that, for example if I have this array:

<?php
    $lol = array(
        "Strawberry/Blueberry/Raspberry",
        "Strawberry, Blueberry, Raspberry",
        "Strawberry & Blueberry & Raspberry",
        "Strawberry and Blueberry and Raspberry",
        "Strawberry, Blueberry and Raspberry",
        "Strawberry, Blueberry, Raspberry",
    );
?>

It would output this:

<?php
    $lol = array(
        array("Strawberry","Blueberry","Raspberry"),
        array("Strawberry","Blueberry","Raspberry"),
        array("Strawberry","Blueberry","Raspberry"),
        array("Strawberry","Blueberry","Raspberry"),
        array("Strawberry","Blueberry","Raspberry"),
        array("Strawberry","Blueberry","Raspberry"),
    );
?>

Is there an efficient way to do this?

user2217162
  • 897
  • 1
  • 9
  • 20

5 Answers5

3
for($i=0;$i<count($lol);$i++){
    $lol[$i] = preg_split("@(\s*and\s*)?[/\s,&]+@", $lol[$i]);
}
Sabuj Hassan
  • 38,281
  • 14
  • 75
  • 85
2

You can replace the delimiters to a common that explode() will accept:

foreach($lol as $key => $current) {
    $bits = explode(',', stri_replace(array('/', '&', 'and'), ',', $current));
    $lol[$key] = $bits;
}
scrowler
  • 24,273
  • 9
  • 60
  • 92
1

You can use preg_split() - then you use a regular expression to say "a or b or c"

Sample:

<?php
    $lol = array(
        "Strawberry/Blueberry/Raspberry",
        "Strawberry, Blueberry, Raspberry",
        "Strawberry & Blueberry & Raspberry",
        "Strawberry and Blueberry and Raspberry",
        "Strawberry, Blueberry and Raspberry",
        "Strawberry, Blueberry, Raspberry",
    );
    $s = "/\/|, | & | and /";
    foreach ($lol as $v) {
      print_r(preg_split($s, $v));
    }
?>

Output:

Array
(
    [0] => Strawberry
    [1] => Blueberry
    [2] => Raspberry
)
Array
(
    [0] => Strawberry
    [1] => Blueberry
    [2] => Raspberry
)
Array
(
    [0] => Strawberry
    [1] => Blueberry
    [2] => Raspberry
)
Array
(
    [0] => Strawberry
    [1] => Blueberry
    [2] => Raspberry
)
Array
(
    [0] => Strawberry
    [1] => Blueberry
    [2] => Raspberry
)
Array
(
    [0] => Strawberry
    [1] => Blueberry
    [2] => Raspberry
)
Floris
  • 45,857
  • 6
  • 70
  • 122
1

You can use preg_split:

$arr = preg_split('~ *(?:[/,&]|and) */i~', $str, -1, PREG_SPLIT_NO_EMPTY) 
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

Try this:

<?php
    $lol = array(
        "Strawberry/Blueberry/Raspberry",
        "Strawberry, Blueberry, Raspberry",
        "Strawberry & Blueberry & Raspberry",
        "Strawberry and Blueberry and Raspberry",
        "Strawberry, Blueberry and Raspberry",
        "Strawberry, Blueberry, Raspberry",
    );
for($i=0;$i<count($lol);$i++){
$tem=str_ireplace("&",",",str_ireplace("/",",",str_ireplace("and",",",$lol[$i])));//first replacing all (& , / , and) with "," then explod with ","
$lol[$i]=explode(",",$tem);}