2011-02-14 133 views
13

如何在substr() PHP函數中使用正則表達式來獲取與模式匹配的子字符串?正則表達式通過php獲取子字符串

編輯:

例如:

$name = 'hello [*kitty*],how good is today'; 

我想要得到的是[....]佔位符之間。

+1

能否請您提供一個樣本輸入 - 輸出?很難告訴你想要實現什麼,如果你想匹配一部分字符串,我懷疑'sub_str`函數是需要的。 `preg_match`就足夠了。 – 2011-02-14 11:23:18

+0

請給你的問題!我們給你的解決方案 – 2011-02-14 11:23:36

+0

[PHP的:如何找到一個字符串中的子字符串的開始和結束?](http://stackoverflow.com/questions/3706175/php-how-to-find-the-beginning字符串的末尾字符串) – outis 2012-07-12 03:19:16

回答

35

substr()只匹配整個字符串。您正在尋找preg_match()

更新

$name = 'hello [*kitty*],how good is today'; 
preg_match('/\[(.*?)\]/', $name, $match); 
var_dump($match); 

可以在$match[1]找到該名稱。我建議你閱讀正則表達式來理解preg_match()

4

試試這個:

$matches = array(); 
preg_match("/\[([^]]*)\]/", 'hello [*kitty*],how good is today', $matches); 
print_r($matches); 

哎呀,現在修好了:)