How to use preg_match with multiple words in PHP?

Asked 2 years ago 134 views 1 answer Modified 18 hours ago
13

I want to search for multiple words in a string using PHP's preg_match() function.

Here's what I'm trying:

$string = "white red green blue";
$pattern = "/red, blue/";
echo preg_match($pattern, $string);

This returns 0, but I expected it to find matches. How do I properly search for multiple words using regular expressions in PHP?

Imran Nadwi
50 reputation

1 Answer

0

You can use multiple words in pattern 2 or more for preg_match, like this:

$string = "white red green blue";

$pattern = "/(red)|(blue)/";

echo preg_match($pattern, $string);

result : 1

CodingerWeb
answered 2 years ago
You can use Markdown to format your answer.
Last edited: 2 years ago
Preview: