开发者

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})$#开发者_Python百科", $item->title);


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜