views:

17

answers:

1

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);
+2  A: 

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?

amphetamachine
Damn, I completely forgot the existence of preg_match, even looking at the PHP manual. I knew there were a better preg_ function for what I wanted to do than preg_split. That's what happens when you stop developing in PHP for a few years :S. Thanks, your solution worked as I wanted.
Nazgulled