【问题标题】:PHP regex preg_match_all: Capturing text between multiple square bracketsPHP regex preg_match_all:捕获多个方括号之间的文本
【发布时间】:2013-04-25 10:24:39
【问题描述】:

我需要捕获一些字符串数组.. 我一直在尝试但我不能:$

我的代码中有这个:

<?php
$feed = "[['2013/04/03',8.300],['2013/04/04',8.320],['2013/04/05',8.400]]";
preg_match_all("/\[(.*?)\]/",$feed,$matches);
print_r($matches);

并且正在返回:

Array
(
    [0] => Array
        (
            [0] => [['2013/04/03',8.300]
            [1] => ['2013/04/04',8.320]
            [2] => ['2013/04/05',8.400]
        )

    [1] => Array
        (
            [0] => ['2013/04/03',8.300
            [1] => '2013/04/04',8.320
            [2] => '2013/04/05',8.400
        )

)

我如何使用 preg_match_all 或 preg_split.. 或返回一个元素数组(如 $matches[1][1] 或 $matches[1][2])所需的任何方法??

我的意思是每个元素的格式应该是:

'2013/04/05',8.400

希望清楚:)

提前致谢!!

【问题讨论】:

  • 我在这里可能完全错了,但这个例子看起来像一个有效的 JSON 数组。做json_decode 然后把它当作一个普通的数组使用不是更容易吗?
  • 您可以使用(?&lt;=^\[|,)\[(.*?)\]
  • 或者让你的正则表达式更具体\[('\d{4}\/\d{2}\/\d{2}',\d+(?:\.\d+)?)\]
  • 哈姆扎!!第二个返回的数组正是我需要的!有可能在一个数组中得到它吗?
  • @lizaaard 抱歉,preg_match_all() 就是这样工作的,所以你必须做类似$array = $matches[1] 的事情;

标签: php regex preg-match-all


【解决方案1】:

如果它恰好是不是一个有效的 json,你可以用字符串做简单的操作。

$arr = explode("],[", trim($str, " []"));

输出将是一个包含类似以下元素的数组:"'2013/04/03',8.300" , "'2013/04/04',8.320"

这将比使用 RegExp 方法的方法快

【讨论】:

  • 我想知道为什么它现在出现在 2017 年的“热门网络问题”中。哈哈
【解决方案2】:

此文本似乎采用了相当规范的格式,例如 JSON。完全可以避免 reg 匹配并使用 json_decode 对其进行解析,尽管必须进行一些小的转换。

// original input
$text = "[['2013/04/03',8.300],['2013/04/04',8.320],['2013/04/05',8.400]]";

// standard transformation to correct ' and / characters
$text = str_replace( array('/', "'"), array('\/', '"'), $text );

// let native PHP take care of understanding the data
$data = json_decode( $text );

这将为您提供包含日期和值的数组数组。 print_r( $data ); 给:

Array (
    [0] => Array (
        [0] => 2013/04/03
        [1] => 8.3
    )
    [1] => Array (
        [0] => 2013/04/04
        [1] => 8.32
    )
    [2] => Array (
        [0] => 2013/04/05
        [1] => 8.4
    )
)

转换将 / 替换为 \/' 替换为 " 以使字符串符合 JSON 标准。或者类似的东西。

【讨论】:

    【解决方案3】:

    你可以试试这个:

    <?php
    $feed = "[['2013/04/03',8.300],['2013/04/04',8.320],['2013/04/05',8.400]]";
    preg_match_all('~\[\K[^[\]]++~', $feed, $matches);
    print_r($matches);
    

    【讨论】:

    • 您的解决方案在第一场比赛中有一个左括号。 [0] => ['2013/04/03',8.300
    • 这正是我所需要的......只是第一个元素有 [ 方括号......但也许我可以在循环时清理它......但可以删除它?
    • @lizaaard:我忘记了课堂上的方括号。已更正。
    猜你喜欢
    • 2012-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-22
    • 2016-06-03
    • 1970-01-01
    相关资源
    最近更新 更多