我需要捕获一些字符串数组..我一直在尝试但我不能:$
我的代码中有这个:
<?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/