When should strip_tags be used instead of str_replace to prevent script injection in PHP?

To prevent script injection in PHP, strip_tags should be used instead of str_replace when you want to remove all HTML tags from a string. Strip_tags is specifically designed for this purpose and is more reliable than using str_replace, which may miss certain variations of HTML tags or inadvertently remove non-dangerous characters.

// Using strip_tags to remove all HTML tags from a string
$unsafeString = "<script>alert('Hello, World!');</script>";
$safeString = strip_tags($unsafeString);
echo $safeString;