How can inline comments in JavaScript be preserved when using the preg_replace function in PHP?

When using the preg_replace function in PHP to manipulate JavaScript code, inline comments in the JavaScript code may be unintentionally removed. To preserve these inline comments, you can use a regular expression pattern that specifically excludes comment characters within strings or regular expressions. This ensures that only actual comments outside of strings or regular expressions are removed.

// Sample JavaScript code with inline comments
$javascriptCode = "var x = 5; // This is a comment\nvar y = 10;";

// Regular expression pattern to exclude comment characters within strings or regular expressions
$pattern = '/(\/\/[^\n\r]*|\/\*.*?\*\/)(*SKIP)(*FAIL)|\/\/[^\n\r]*/';

// Replace all occurrences of 'var' with 'let' while preserving inline comments
$newCode = preg_replace($pattern, '', $javascriptCode);

echo $newCode;