Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 456
sultan Avatar asked Mar 26 '12 13:03

sultan


People also ask

How do I match a string in PHP?

The strcmp() function compares two strings. Note: The strcmp() function is binary-safe and case-sensitive. Tip: This function is similar to the strncmp() function, with the difference that you can specify the number of characters from each string to be used in the comparison with strncmp().

How Preg_match () and Preg_split () function works *?

How Preg_match () and Preg_split () function works *? preg_match – This function is used to match against a pattern in a string. It returns true if a match is found and false if no match is found. preg_split – This function is used to match against a pattern in a string and then splits the results into a numeric array.

Does PHP support regex?

In PHP, regular expressions are strings composed of delimiters, a pattern and optional modifiers. $exp = "/w3schools/i"; In the example above, / is the delimiter, w3schools is the pattern that is being searched for, and i is a modifier that makes the search case-insensitive.

How do I match a character in PHP?

preg_match() in PHP – this function is used to perform pattern matching in PHP on a string. It returns true if a match is found and false if a match is not found. preg_replace() in PHP – this function is used to perform a pattern match on a string and then replace the match with the specified text.


2 Answers

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

preg_match("|" . preg_quote($str, "|") . "|", $content->content)
like image 62
piotrekkr Avatar answered Oct 17 '22 09:10

piotrekkr


This worked for me

$pattern = "/" . preg_quote($source, "/") . "/";
like image 30
Abdutahir Avatar answered Oct 17 '22 09:10

Abdutahir