在PHP

2010-09-12 71 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