我想在Wordpress标签<! - nextpage - >中分割一个字符串。 唯一的区别是我的标签将包含当前页面的标题。 例如。 <! - 我的下一页标题 - >
我有这段代码:
$str = 'lorem<!--title1-->ipsum<!--title2-->dolor<!--title3-->sit<!--title4-->amet<!--title5-->consectetur';
$res = preg_split('/<\!--(.*?)-->/', $str, null, PREG_SPLIT_DELIM_CAPTURE);
返回:
Array
(
[0] => lorem
[1] => title1
[2] => ipsum
[3] => title2
[4] => dolor
[5] => title3
[6] => sit
[7] => title4
[8] => amet
[9] => title5
[10] => consectetur
)
我的目标是:
Array
(
[0] => Array
(
[0] => lorem
)
[1] => Array
(
[0] => title1
[1] => ipsum
)
[2] => Array
(
[0] => title2
[1] => dolor
)
[3] => Array
(
[0] => title3
[1] => sit
)
[4] => Array
(
[0] => title4
[1] => amet
)
[5] => Array
(
[0] => title5
[1] => consectetur
)
)
答案 0 :(得分:0)
您可以将preg_match_all与以下正则表达式一起使用:
(?:<\!--(.*?)-->)?(.+?)(?=<!--|$)
请参阅demo
PHP示例代码:
<?php
$re = "/(?:<\\!--(.*?)-->)?(.+?)(?=<!--|$)/";
$str = "lorem<!--title1-->ipsum<!--title2-->dolor<!--title3-->sit<!--title4-->amet<!--title5-->consectetur";
preg_match_all($re, $str, $matches);
$arr = array();
$first = false;
for ($i = 0; $i < count($matches[0]); $i++) {
if ($first) {
array_push($arr, array($matches[1][$i],$matches[2][$i] ));
}
else {
$first = true;
array_push($arr, array($matches[2][$i]));
}
}
print_r($arr);
?>
结果是:
Array
(
[0] => Array
(
[0] => lorem
)
[1] => Array
(
[0] => title1
[1] => ipsum
)
[2] => Array
(
[0] => title2
[1] => dolor
)
[3] => Array
(
[0] => title3
[1] => sit
)
[4] => Array
(
[0] => title4
[1] => amet
)
[5] => Array
(
[0] => title5
[1] => consectetur
)
)