我有一个字符串,我想用三种不同的模式爆炸。该字符串看起来像:
country:00/00/00->link:00/00/00->link2
country2:00/00/00->link3:00/00/00->link4
我想得到这两个字符串的不同部分。这两行由 / n 分隔,日期用分隔:,与日期相关联的链接用 - > 分隔
一开始我在换行符中爆炸
$var = explode("\n", $var);
但是当我试图再次爆炸这个字符串时,我收到一个错误:* preg_split()期望参数2是字符串,给定数组*
我如何获得不同的部分?
提前致谢。
答案 0 :(得分:2)
请考虑使用preg_split
,而不是preg_match
。你可以把它写成一个大的正则表达式。
<?php
// Implicit newline. Adding \n would make an empty spot in the array
$str = "country:00/00/00->link:00/00/00->link2
country2:00/00/00->link3:00/00/00->link4";
$arr = split("\n", $str);
for ($i = 0; $i < count($arr); $i++) {
preg_match("/^(\w+)\:(\d\d\/\d\d\/\d\d)->(\w+)\:(\d\d\/\d\d\/\d\d)->(\w+)/", $arr[$i], $matches);
print_r($matches);
}
?>
输出:
Array
(
[0] => country:00/00/00->link:00/00/00->link2
[1] => country
[2] => 00/00/00
[3] => link
[4] => 00/00/00
[5] => link2
)
Array
(
[0] => country2:00/00/00->link3:00/00/00->link4
[1] => country2
[2] => 00/00/00
[3] => link3
[4] => 00/00/00
[5] => link4
)
修改强>
在您的评论中,您发布的是4位数的日期,而在您的问题中,他们只有2位数。
因此您需要将正则表达式更改为:
/^(\w+)\:(\d\d\/\d\d\/\d\d\d\d)->(\w+)\:(\d\d\/\d\d\/\d\d\d\d)->(\w+)/
答案 1 :(得分:0)
如何使用preg_match_all
:
<?php
$data =<<<ENDDATA
country:00/00/00->link:00/00/00->link2
country2:00/00/00->link3:00/00/00->link4
ENDDATA;
preg_match_all('#(\d{2}/\d{2}/\d{2})->(.[^:\n]+)#', $data, $matches);
print_r($matches);
给出以下结果:
Array
(
[0] => Array
(
[0] => 00/00/00->link
[1] => 00/00/00->link2
[2] => 00/00/00->link3
[3] => 00/00/00->link4
)
[1] => Array
(
[0] => 00/00/00
[1] => 00/00/00
[2] => 00/00/00
[3] => 00/00/00
)
[2] => Array
(
[0] => link
[1] => link2
[2] => link3
[3] => link4
)
)
答案 2 :(得分:0)
你的问题是,在第一次使用爆炸后,它变成了一个数组并且爆炸功能connat爆炸了一个数组。你需要使用循环probablr for循环来定位数组元素,然后对这些元素使用explode函数,你将拥有它。 见下面的例子:
<?php
$val="abc~~~def~~~ghi@@@@jkl~~~mno~~~pqr@@@stu~~~vwx~~~yz1";
$val=explode("@@@@", $val);
//result will be
$valWillBe=array(3) {
[0]=>'abc~~~def~~~ghi',
[1]=>'jkl~~~mno~~~pqr',
[2]=>'stu~~~vwx~~~yz1'
}
//if you want to explode again you use a loop
for($r=0; $r<sizeof($val); $r++){
$val[$r]=explode("~~~", $val[$r]);
}
//now you have your string exploded all in places.
?>