简体   繁体   English

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

[英]Match substring with special characters in a string

I ran into a regex challenge and so far couldn't figure out the solution. 我遇到了一个正则表达式挑战,但到目前为止还找不到解决方案。

I have a string for example like this: 我有一个像这样的字符串:

&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.";

And I would like to preg_match only this part: preg_match(/'![bibendum auctor]/); 我只想preg_match这部分: preg_match(/'![bibendum auctor]/);
As you can see, there are some special characters inside the string and this fails regexp to match the query. 如您所见,字符串中包含一些特殊字符,这使regexp无法匹配查询。

I cannot use preg_quote() , as I don't want to escape the special characters at other parts of the whole string. 我不能使用preg_quote() ,因为我不想在整个字符串的其他部分转义特殊字符。

You can match anything in square brackets preceded by exclamation mark like this: 您可以匹配方括号中带有惊叹号的任何内容,如下所示:

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

working example 工作实例

edit: if you want to match the exact phrase as you've tried you have to escape the brackets like thi: 编辑:如果您想像尝试的那样匹配确切的短语,则必须像这样删除括号:

/'!\[bibendum auctor\]/

example

You can use preg_quote on the string you are searching for like this: 您可以在要搜索的字符串上使用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);

Output: 输出:

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

(In case you're wondering the <<<EOT is heredoc syntax - I just used it so I didn't have to escape all the quotes in the string) (如果您想知道<<<EOTheredoc语法 -我只是使用了它,所以我不必转义字符串中的所有引号)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM