php - division string using regular expressions -
i split string in wordpress tag <!--nextpage-->. difference tag contain title of current page. eg. <!--my title of next page-->
i have code:
$str = 'lorem<!--title1-->ipsum<!--title2-->dolor<!--title3-->sit<!--title4-->amet<!--title5-->consectetur'; $res = preg_split('/<\!--(.*?)-->/', $str, null, preg_split_delim_capture);
which returns:
array ( [0] => lorem [1] => title1 [2] => ipsum [3] => title2 [4] => dolor [5] => title3 [6] => sit [7] => title4 [8] => amet [9] => title5 [10] => consectetur )
my aim is:
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 ) )
you can use preg_match_all following regex:
(?:<\!--(.*?)-->)?(.+?)(?=<!--|$)
see demo
php sample code:
<?php $re = "/(?:<\\!--(.*?)-->)?(.+?)(?=<!--|$)/"; $str = "lorem<!--title1-->ipsum<!--title2-->dolor<!--title3-->sit<!--title4-->amet<!--title5-->consectetur"; preg_match_all($re, $str, $matches); $arr = array(); $first = false; ($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); ?>
results are:
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 ) )
Comments
Post a Comment