This question already has an answer here:
I am trying to explode() with multiple delimiters.
With the delimiters:
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?
</div>
for($i=0;$i<count($lol);$i++){
$lol[$i] = preg_split("@(\s*and\s*)?[/\s,&]+@", $lol[$i]);
}
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
)
You can use preg_split
:
$arr = preg_split('~ *(?:[/,&]|and) */i~', $str, -1, PREG_SPLIT_NO_EMPTY)
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;
}
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);}