2014-09-05 88 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