PHP: string to regex

依然范特西╮ 提交于 2019-12-08 15:39:18

问题


I try use string as a regular expression pattern but I've following errors

PHP Warning:  preg_match(): Unknown modifier '>' in /Applications/MAMP/htdocs/cruncher/Plugins/wordpress/WPDetect.php on line 22
PHP Warning:  preg_match(): Unknown modifier '/' in /Applications/MAMP/htdocs/cruncher/Plugins/wordpress/WPDetect.php on line 22

The code

$str = "<meta name=\"generator\" content=\"WordPress.com\" />"
preg_match("/".$str."/", $content->content)

I also tried to use preg_quote function but I've similar problems.

What is the correct way to make it work?

Sultan


回答1:


Use preg_quote function and pattern enclosed with |...|

preg_match("|" . preg_quote($str, "|") . "|", $content->content)



回答2:


This worked for me

$pattern = "/" . preg_quote($source, "/") . "/";



回答3:


You must escape your limiter

$str = "<meta name=\"generator\" content=\"WordPress.com\" \/>"



回答4:


Regular expression contain a set of special char like \ - * . ? $ ^ + () []and more, you have to escape them from your string before using it (you esacpe by adding a \ before the char)



来源:https://stackoverflow.com/questions/9873144/php-string-to-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!