Skip to content
PHP Logo

How can regular expressions be used to search for words within a string in PHP?

Regular expressions can be used in PHP to search for specific words within a string by using the `preg_match()` function. This function takes a regular expression pattern and a string as input, and returns true if the pattern is found within the string. To search for a specific word, you can use the pattern `/\bword\b/`, where `word` is the word you are looking for. This pattern uses word boundaries to ensure that the word is matched as a whole word and not as a part of another word.

php
$string = "This is a sample string containing the word 'example'.";
$word = 'example';

if (preg_match("/\b$word\b/", $string)) {
    echo "The word '$word' was found in the string.";
} else {
    echo "The word '$word' was not found in the string.";
}