PHP 正则表达式 preg_match_all : Capturing text between multiple square brackets

标签 php regex preg-match-all

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

我的代码中有这个:

<?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。完全可以避免 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 . 或者类似的东西。

关于PHP 正则表达式 preg_match_all : Capturing text between multiple square brackets,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16317857/

相关文章:

javascript - 如何使用 PHP 在 JavaScript (Highcharts) 中设置值

php - 传递一个字符串作为参数

php - preg_match 获取文本

php - 在 WHERE 子句中正确使用数组值

php - fatal error 未捕获异常无法打开 INI 文件

java - 在 PHP 中制作 Web 服务以向 Java 提供信息

php - 我在哪里可以找到 RedHat 7 的 php-pgsql 包?

Java 和 .Net 正则表达式

python - 包含 2 个或更多 2 个字母元音序列的匹配单词

python - Python正则表达式,匹配A和B之间的任何内容,除非C