在 php 中分解多个分隔符
explode multiple delimiters in php
我的数组看起来像:
{flower},{animals},{food},{people},{trees}
我想和{
、,
&}
一起爆炸。
我的输出应该只包含大括号内的单词。
我的代码:
$array = explode("},{", $list);
执行此代码后 $array 将是
$array = Array (
[0] => {flower
[1] => animals
[2] => food
[3] => people
[4] => trees}
)
但输出数组应该是:
$array = Array (
[0] => flower
[1] => animals
[2] => food
[3] => people
[4] => trees
)
任何人都可以告诉我如何修改我的代码以获得这个数组吗?
我会选择 preg_split 如下所示
<?php
$list = "{flower},{animals},{food},{people},{trees}";
$array = preg_split('/[},{]/', $list, 0, PREG_SPLIT_NO_EMPTY);
print_r($array);
?>
输出为
Array
(
[0] => flower
[1] => animals
[2] => food
[3] => people
[4] => trees
)
您可以尝试使用正则表达式而不是拆分字符串来提取单词:
$list = "{flower},{animals},{food},{people},{trees}";
// Match anything between curly brackets
// The "U" flag prevents the regex to make a single match with the first and last brackets
preg_match_all('~{(.+)}~U', $list, $result);
// Only keep the 1st capturing group
$words = $result[1];
var_dump($words);
输出:
array(5) {
[0]=>
string(6) "flower"
[1]=>
string(7) "animals"
[2]=>
string(4) "food"
[3]=>
string(6) "people"
[4]=>
string(5) "trees"
}
我的数组看起来像:
{flower},{animals},{food},{people},{trees}
我想和{
、,
&}
一起爆炸。
我的输出应该只包含大括号内的单词。
我的代码:
$array = explode("},{", $list);
执行此代码后 $array 将是
$array = Array (
[0] => {flower
[1] => animals
[2] => food
[3] => people
[4] => trees}
)
但输出数组应该是:
$array = Array (
[0] => flower
[1] => animals
[2] => food
[3] => people
[4] => trees
)
任何人都可以告诉我如何修改我的代码以获得这个数组吗?
我会选择 preg_split 如下所示
<?php
$list = "{flower},{animals},{food},{people},{trees}";
$array = preg_split('/[},{]/', $list, 0, PREG_SPLIT_NO_EMPTY);
print_r($array);
?>
输出为
Array
(
[0] => flower
[1] => animals
[2] => food
[3] => people
[4] => trees
)
您可以尝试使用正则表达式而不是拆分字符串来提取单词:
$list = "{flower},{animals},{food},{people},{trees}";
// Match anything between curly brackets
// The "U" flag prevents the regex to make a single match with the first and last brackets
preg_match_all('~{(.+)}~U', $list, $result);
// Only keep the 1st capturing group
$words = $result[1];
var_dump($words);
输出:
array(5) {
[0]=>
string(6) "flower"
[1]=>
string(7) "animals"
[2]=>
string(4) "food"
[3]=>
string(6) "people"
[4]=>
string(5) "trees"
}