sultan
sultan

Reputation: 6058

PHP: string to regex

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

Upvotes: 12

Views: 14486

Answers (4)

piotrekkr
piotrekkr

Reputation: 3181

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

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

Upvotes: 16

Abdutahir
Abdutahir

Reputation: 173

This worked for me

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

Upvotes: 6

grifos
grifos

Reputation: 3381

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)

Upvotes: 0

Tchoupi
Tchoupi

Reputation: 14681

You must escape your limiter

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

Upvotes: 0

Related Questions