将子字符串与字符串中的特殊字符匹配

时间:2014-05-23 12:10:04

标签: php regex

我遇到了正则表达式的挑战,到目前为止还无法找到解决方案。

我有一个字符串,例如:

&str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce malesuada sit amet risus vel ultricies. Quisque pretium leo in sem sodales, in ullamcorper dolor aliquet. Duis at massa felis. Pellentesque fringilla **'![bibendum auctor]**. Nunc scelerisque aliquam sem. Nam pharetra eros quis libero molestie iaculis. Etiam vehicula blandit ipsum in sodales. Nulla tempus cursus lacus, sed cursus ligula consequat at. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Suspendisse at blandit" ipsum, sed porta urna. Vesti&&&&bulum turpis risus, ultricies at sapien id, vehicula venenatis neque.";

我想preg_match只有这一部分:preg_match(/'![bibendum auctor]/);
如您所见,字符串中有一些特殊字符,这使得regexp无法匹配查询。

我无法使用preg_quote(),因为我不想在整个字符串的其他部分转义特殊字符。

2 个答案:

答案 0 :(得分:1)

您可以匹配带有感叹号的方括号中的任何内容,如下所示:

/!\[([^\]]+)\]/

working example

编辑:如果你想匹配确切的短语,你已经尝试过必须像thi一样逃避括号:

/'!\[bibendum auctor\]/

example

答案 1 :(得分:0)

您可以对要搜索的字符串使用preg_quote,如下所示:

$str = <<<EOT
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce malesuada sit amet risus vel ultricies. Quisque pretium leo in sem sodales, in ullamcorper dolor aliquet. Duis at massa felis. Pellentesque fringilla **'![bibendum auctor]**. Nunc scelerisque aliquam sem. Nam pharetra eros quis libero molestie iaculis. Etiam vehicula blandit ipsum in sodales. Nulla tempus cursus lacus, sed cursus ligula consequat at. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Suspendisse at blandit" ipsum, sed porta urna. Vesti&&&&bulum turpis risus, ultricies at sapien id, vehicula venenatis neque.
EOT;

$search = preg_quote('![bibendum auctor]', '/');

preg_match("/$search/", $str, $matches);
print_r($matches);

输出:

Array ( [0] => ![bibendum auctor] ) 

(如果您想知道<<<EOTheredoc syntax - 我刚刚使用它,所以我没有必要转义字符串中的所有引号)