在PHP

2010-09-12 70 views
1
以使preg_split正则表达式有问题

我有以下输入:在PHP

几个字 - 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); 

回答

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

认为你可以搜集你需要的是结构的信息?

+0

该死的,我完全忘了preg_match的存在,甚至在看PHP手册。我知道对于我想要做的比preg_split有更好的preg_功能。这就是当你停止PHP开发几年时发生的事情:S。谢谢,您的解决方案按我的意愿工作。 – 2010-09-12 10:35:03