【问题标题】:Regex not working properly in PHP正则表达式在 PHP 中无法正常工作
【发布时间】:2014-02-22 21:15:12
【问题描述】:

我有这些数据:

{"names":["George","Eric","Alice"]}

我想使用preg_match_all 过滤掉引号之间的单词,如下所示:

$s = $data;

if (preg_match_all('/"([^:]*)"/', $s, $matches)) {
        echo join("\n", $matches[1]);
}

但这是输出names George","Eric","Alice 我尝试了很多东西但我无法弄清楚。

【问题讨论】:

  • 为什么不使用 JSON 解析器?
  • json_decode() 救援print_r(json_decode('{"names":["George","Eric","Alice"]}', true));
  • 它的 JSON 但我在我的项目中使用它作为纯文本
  • @Youss 好的,你之前没有提到过。但是您可以使用foreach($arr, $key => $value){} 循环,它实际上取决于您的源的随机性。无论如何,不​​“推荐”使用正则表达式解析 JSON,但仍然可以使用正则表达式
  • @HamZa 感谢您的输入 +1

标签: php regex preg-match-all


【解决方案1】:

由于您的数据是 json 格式,您应该将其视为 json,而不是使用用于字符串的正则表达式处理它。试试这个:

$json = '{"names":["George","Eric","Alice"]}';
$data = json_decode($json, true);
foreach($data['names'] as $item) echo "$item\n";

或者没有硬编码的“名称”:

$json = '{"names":["George","Eric","Alice"]}';
$data = json_decode($json, true);
foreach($data as $arr) foreach($arr as $item) echo "$item\n";

【讨论】:

    【解决方案2】:

    * 匹配贪心(尽可能)。使用非greey版本:*?

    if (preg_match_all('/"([^:]*?)"/', $s, $matches)) {
        echo join("\n", $matches[1]);
    }
    

    输出:

    names
    George
    Eric
    Alice
    

    更新

    json_decode 更适合这种工作。请尝试以下操作:

    foreach (json_decode($s, true) as $key => $value) {
        echo $key . "\n";
        echo join("\n", $value);
    }
    

    【讨论】:

    • 非常感谢:) 这可以完成工作
    • 不要将 json 数据视为字符串!不好的做法。
    • @Roebie,我更新了答案。我只是想告诉OP得到结果的原因。
    • @falsetru:对不起,我们的cmets越界了。
    • 其实你需要一个complexer regex来考虑转义双引号(?<!\\)"((?:[^\\]|\\.)*?)"
    【解决方案3】:

    试试这个

    $strContent = '{"names":["George","Eric","Alice"]}';
    $strRegex = '%\"(.+?)\"%s';
    if (preg_match_all($strRegex, $strContent, $arrMatches))
    {
        var_dump($arrMatches[1]);
    }
    

    【讨论】:

      【解决方案4】:

      这实际上是 JSON 字符串,使用 json_decode 解析它,而不是使用正则表达式:

      print_r(json_decode('{"names":["George","Eric","Alice"]}', true));
      

      输出:

      Array
      (
          [names] => Array
              (
                  [0] => George
                  [1] => Eric
                  [2] => Alice
              )
      
      )
      

      【讨论】:

      • 问题是我将其输出为纯文本而不是 json。我真的只需要单词而不是引号、括号等。 (我的项目要求它是纯文本..)
      • 然后json_decode 可以用作:print_r(json_decode($data, true)); 其中$data 是包含此纯文本的变量。这比正则表达式更清洁、更安全。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-25
      • 2016-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多