How can special characters, such as slashes, in JavaScript comments be properly handled when using preg_replace in PHP?

Special characters, such as slashes, in JavaScript comments can cause issues when using preg_replace in PHP because the slashes are considered escape characters in regular expressions. To properly handle special characters in JavaScript comments, you can use the preg_quote function in PHP to escape the special characters before using preg_replace.

$comment = "// This is a comment with special characters / and \n";
$escaped_comment = preg_quote($comment, '/');
$pattern = '/\/\/.*$/m';
$replacement = '';
$cleaned_comment = preg_replace($pattern, $replacement, $escaped_comment);
echo $cleaned_comment;