How can regex be used to search for a specific word that is not within an HTML tag?
To search for a specific word that is not within an HTML tag using regex, we can use a negative lookahead assertion to exclude matches that occur within HTML tags. This allows us to search for the word only outside of any HTML tags.
$html = '<p>This is a sample <b>HTML</b> text with the word example.</p>';
$word_to_search = 'example';
$pattern = '/(?<!<[^>]+)' . preg_quote($word_to_search, '/') . '(?!<\/[^>]+)/';
if (preg_match($pattern, $html, $matches)) {
echo "The word '$word_to_search' was found outside of HTML tags.";
} else {
echo "The word '$word_to_search' was not found outside of HTML tags.";
}