在PHP中使用preg_split的正则表达式有问题

时间:2010-09-12 04:19:20

标签: php regex preg-split

我有以下输入:

几句话 - 25 更多 - 单词 - 7 另一套 - 字 - 13 -

我需要分成这个:

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

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

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

我正在尝试使用preg_split,但我总是想念结束号码,我的尝试:

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

1 个答案:

答案 0 :(得分:2)

使用单引号。我不能强调这一点。 $也是字符串结尾元字符。分裂时我怀疑你想要这个。

您可能希望使用更像preg_match_all的内容进行匹配:

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

产地:

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"
  }
}

您认为可以从该结构中收集所需的信息吗?