2017-10-09 193 views
-5

我尝试了很多组合来创建正确的正则表达式,但我失败了。如何创建正确的RegEx?

我想读此,输入:

[@Homer Jay Simpson](id:homer) is a good guy. 

,并得到

Array (
    [0] => "[@Homer Jay Simpson](id:homer)", 
    [1] => "Homer Jay Simpson", 
    [2] => "homer" 
) 

的感谢!

+0

我不确定@rika正则表达式是一个不错的选择更好地尝试使用括号来爆炸字符串 – shashi

回答

2

摆弄了一点点后,这个正则表达式会为你工作:

\[@([^\]]+)\]\(id:([^)]+)\) 

使用,如:

$str = "[@Homer Jay Simpson](id:homer) is a good guy."; 
preg_match('#\[@([^\]]+)\]\(id:([^)]+)\)#', $str, $matches); 
print_r($matches); 

产地:

Array 
(
    [0] => [@Homer Jay Simpson](id:homer) 
    [1] => Homer Jay Simpson 
    [2] => homer 
) 

小费时创建正则表达式模式,从小处开始构建到它的末端。我开始只匹配方括号\[@([^\]]+)\]的内部,然后拼凑在其余的部分。完整的日志here

0

http://www.phpliveregex.com/p/lAg

preg_match("/\[\@(.*?)\]\(id:(.*?)\)/", $str, $matches); 
Var_dump($matches); 

这将捕获括号[]()之间是什么。
\使reges读取符号为文字。
.*?表示懒惰捕捉任何东西,如果有任何长度。