What are some best practices for handling escape sequences and special characters in PHP when developing a syntax highlighter?

When developing a syntax highlighter in PHP, it's important to properly handle escape sequences and special characters to ensure accurate highlighting of code. One way to do this is by using the PHP function htmlspecialchars() to convert special characters to HTML entities. This function will escape characters like <, >, ", ', and & which could otherwise interfere with the syntax highlighting process.

// Example code snippet to handle escape sequences and special characters in PHP syntax highlighter
$code = &quot;echo &#039;Hello, world!&#039;;&quot;;
$highlightedCode = highlight_string($code, true);
echo htmlspecialchars($highlightedCode);