2014-09-05 84 views
2

我一直坐幾個小時才能找出php中preg_match_all函數的regExp。 我的問題是,我從字符串whant兩個不同的東西。preg_match_all括號內外的單詞

假設你有字符串「代碼很有趣[對大腦有益。]但是[大腦]累了。」

我需要從括號內的所有單詞和括號中的文本一起作爲一個字符串的數組。

像這樣的事情

[0] => Code 
[1] => is 
[2] => fun 
[3] => and good for the brain. 
[4] => But 
[5] => the 
[6] => brain is 
[7] => tired. 

幫助非常感謝。

回答

3

你可以試試下面的正則表達式也,

(?<=\[)[^\]]*|[.\w]+ 

DEMO

代碼:

<?php 
$data = "Code is fun [and good for the brain.] But the [brain is] tired."; 
$regex = '~(?<=\[)[^\]]*|[.\w]+~'; 
preg_match_all($regex, $data, $matches); 
print_r($matches); 
?> 

輸出:

Array 
(
    [0] => Array 
     (
      [0] => Code 
      [1] => is 
      [2] => fun 
      [3] => and good for the brain. 
      [4] => But 
      [5] => the 
      [6] => brain is 
      [7] => tired. 
     ) 

) 

第一lookbind (?<=\[)[^\]]*所有這些都是字符匹配存在於大括號[]內,並且第二個[.\w]+匹配來自剩餘字符串的一個或多個單詞字符或點。

+0

像魅力一樣工作 – Sebastian 2014-09-08 06:55:01

+0

不客氣:-) – 2014-09-08 07:01:14

1

您可以使用以下正則表達式:

(?:\[([\w .!?]+)\]+|(\w+)) 

正則表達式包含兩個交替:一個相匹配的兩個方括號內的一切,和一個捕捉每一個其它字。

這假定該方括號內的部分不包含除字母,數字,_!.,並?其他任何字符。如果你需要添加更多的標點符號,應該很容易將它們添加到字符類中。

如果你不想成爲具體什麼應該被捕獲,那麼你可以使用一個否定的字符類,而不是 - 指定哪些匹配,而不是指定匹配的內容。然後,表達變成:(?:\[([^\[\]]+)\]|(\w+))

可視化:

說明:

(?:    # Begin non-capturing group 
    \[    # Match a literal '[' 
    (   # Start capturing group 1 
     [\w .!?]+ #  Match everything in between '[' and ']' 
    )   # End capturing group 1 
    \]    # Match literal ']' 
    |    # OR 
    (    # Begin capturing group 2 
    \w+   #  Match rest of the words 
)    # End capturing group 2 
)    # End non-capturing group 

Demo

+0

您可以使用分支重置來捕獲group1中的匹配:(?| \ [([\ w。!?] +)\] + |(\ w +)) – 2014-09-05 15:37:42