我想像在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
)
)
您可以将preg_match_all与以下正则表达式配合使用:
(?:<\!--(.*?)-->)?(.+?)(?=<!--|$)
观看演示
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
)
)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句