samedi 25 avril 2015

division string using regular expressions


I would like to split a string like in Wordpress tag <!--nextpage-->. The only difference is that my tag will contain the title of the current page. eg. <!--my title of next page-->

I have this 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
        )    
)


Aucun commentaire:

Enregistrer un commentaire