我需要捕获一些字符串数组。。我一直在尝试,但我做不到:$
我的代码里有这个:
<?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
$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);
如果它恰好是而不是有效的json,则可以使用字符串进行简单的操作。
$arr = explode("],[", trim($str, " []"));
输出将是一个具有类似元素的数组:"'2013/04/03',8.300" , "'2013/04/04',8.320"
这将比使用RegExp方法快次。