我正在尝试使用多个分隔符来爆炸()。
使用分隔符:
所以,例如,如果我有这个数组:
<?php
$lol = array(
"Strawberry/Blueberry/Raspberry",
"Strawberry, Blueberry, Raspberry",
"Strawberry & Blueberry & Raspberry",
"Strawberry and Blueberry and Raspberry",
"Strawberry, Blueberry and Raspberry",
"Strawberry, Blueberry, Raspberry",
);
?>
会输出:
<?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"),
);
?>
有一种有效的方法吗?
答案 0 :(得分:2)
for($i=0;$i<count($lol);$i++){
$lol[$i] = preg_split("@(\s*and\s*)?[/\s,&]+@", $lol[$i]);
}
答案 1 :(得分:1)
您可以使用preg_split()
- 然后使用正则表达式来表示“a或b或c”
样品:
<?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));
}
?>
输出:
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
)
答案 2 :(得分:1)
您可以使用preg_split
:
$arr = preg_split('~ *(?:[/,&]|and) */i~', $str, -1, PREG_SPLIT_NO_EMPTY)
答案 3 :(得分:1)
您可以将分隔符替换为explode()
将接受的公共分区:
foreach($lol as $key => $current) {
$bits = explode(',', stri_replace(array('/', '&', 'and'), ',', $current));
$lol[$key] = $bits;
}
答案 4 :(得分:0)
试试这个:
<?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);}