Search code examples
phpregexpreg-split

Having problems with regular expressions with preg_split in PHP


I have the following input:

a few words - 25 some more - words - 7 another - set of - words - 13

And I need to split into this:

[0] = "a few words"
[1] = 25

[0] = "some more - words"
[1] = 7

[0] = "another - set of - words"
[1] = 13

I'm trying to use preg_split but I always miss the ending number, my attempt:

$item = preg_split("#\s-\s(\d{1,2})$#", $item->title);

Solution

  • Use single quotes. I cannot stress this enough. Also $ is the string-end metacharacter. I doubt you want this when splitting.

    You may want to use something more like preg_match_all for your matching:

    $matches = array();
    preg_match_all('#(.*?)\s-\s(\d{1,2})\s*#', $item->title, $matches);
    var_dump($matches);
    

    Produces:

    array(3) {
      [0]=>
      array(3) {
        [0]=>
        string(17) "a few words - 25 "
        [1]=>
        string(22) "some more - words - 7 "
        [2]=>
        string(29) "another - set of - words - 13"
      }
      [1]=>
      array(3) {
        [0]=>
        string(11) "a few words"
        [1]=>
        string(17) "some more - words"
        [2]=>
        string(24) "another - set of - words"
      }
      [2]=>
      array(3) {
        [0]=>
        string(2) "25"
        [1]=>
        string(1) "7"
        [2]=>
        string(2) "13"
      }
    }
    

    Think you can glean the information you need out of that structure?