【问题标题】:explode multiple delimiters in php在php中分解多个分隔符
【发布时间】:2021-10-25 08:30:24
【问题描述】:

我的数组看起来像:

{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 
)

谁能告诉我如何修改我的代码来获取这个数组?

【问题讨论】:

  • 正则表达式匹配更好
  • 你可以先用trim剪掉外面的花括号,explode("},{", trim($list, '{}'))

标签: php arrays explode


【解决方案1】:

您可以尝试使用 RegEx 提取单词而不是拆分字符串:

$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"
}

【讨论】:

    【解决方案2】:

    我会像下面那样选择 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
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-24
      • 1970-01-01
      • 2023-04-02
      相关资源
      最近更新 更多