我有一根绳子,我想用三种不同的模式爆炸。字符串看起来像:
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 是字符串,数组给定*
我怎样才能得到不同的零件?
提前谢谢。
Ideone link
考虑使用 preg_match
,而不是使用 preg_split
。您可以将其编写为一个大正则表达式。
<?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+)/
如何使用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
)
)
你的问题是第一次使用爆炸后,它变成了一个数组和爆炸函数connat分解一个数组。您需要使用针对数组枚举器的循环的循环概率,然后在这些元素上使用爆炸函数,您将拥有它。请参阅下面的示例:
<?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.
?>