How to use preg_match with multiple words in PHP?

Asked 2 years ago 207 views 1 answer Modified 5 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: ```php $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?
shama-naaz
50 reputation

1 Answer

0
You can use multiple words in pattern 2 or more for preg_match, like this: ```php $string = "white red green blue"; $pattern = "/(red)|(blue)/"; echo preg_match($pattern, $string); ``` This will return 1 if either "red" or "blue" is found in the string. **Explanation:** - The pipe symbol `|` acts as an OR operator in regex - `(red)|(blue)` means match "red" OR "blue" - You can add more words: `/(red)|(blue)|(green)/` **Alternative simpler syntax:** ```php $pattern = "/red|blue/"; ``` Both patterns work the same way. The second one is cleaner when you don't need capturing groups.
imran-nadwi
answered 1 years ago
You can use Markdown to format your answer.
Last edited: 1 years ago
Preview: