Are there any best practices for using htmlentities() in conjunction with preg_match() in PHP?

When using htmlentities() in conjunction with preg_match() in PHP, it is important to be mindful of the encoding and escaping of characters. It is recommended to apply htmlentities() before using preg_match() to ensure that special characters are properly encoded and do not interfere with the regular expression matching. This helps prevent any unexpected behavior or vulnerabilities in your code.

$string = "<script>alert('Hello!');</script>";
$encodedString = htmlentities($string, ENT_QUOTES);

$pattern = "/<.+>/";
if (preg_match($pattern, $encodedString)) {
    echo "Match found!";
} else {
    echo "No match found.";
}