Syntax highlighting is an important feature when building development tools, blog engines, or code sharing platforms. Although PHP itself does not have ready-made highlighting libraries like the front-end (such as Prism.js or Highlight.js), we can use pure PHP to implement basic syntax highlighting. The preg_replace_callback_array() function provides a concise and elegant way to match different code elements and wrap them in different colors or labels.
This article will explain how to use preg_replace_callback_array() to implement a simple PHP syntax highlighter.
preg_replace_callback_array() is a function introduced in PHP 7.0. It allows you to specify different callback functions for multiple regular expressions at once. This requires a call for each rule once compared to the old method preg_replace_callback() , which has a clearer structure and higher efficiency.
The basic syntax is as follows:
preg_replace_callback_array(array $patterns_and_callbacks, string $subject);
We want to highlight the following elements:
PHP keywords (such as function , echo , if, etc.)
String (content surrounded by odd and double quotes)
Comments ( // start or /* ... */ )
Variable (identifier starting with $ )
<?php
$code = <<<'PHP'
<?php
// This is a comment
function sayHello($name) {
echo "Hello, $name!";
}
PHP;
function highlight_php_code(string $code): string {
$keywords = ['function', 'echo', 'if', 'else', 'return'];
$keywordPattern = '/\b(' . implode('|', $keywords) . ')\b/';
$stringPattern = '/([\'"])(.*?)(\1)/s';
$commentPattern = '/(\/\/.*?$|\/\*.*?\*\/)/ms';
$variablePattern = '/(\$\w+)/';
$patterns = [
$keywordPattern => function ($matches) {
return '<span style="color: blue; font-weight: bold;">' . $matches[0] . '</span>';
},
$stringPattern => function ($matches) {
return '<span style="color: green;">' . htmlspecialchars($matches[0]) . '</span>';
},
$commentPattern => function ($matches) {
return '<span style="color: gray; font-style: italic;">' . htmlspecialchars($matches[0]) . '</span>';
},
$variablePattern => function ($matches) {
return '<span style="color: darkorange;">' . $matches[0] . '</span>';
},
];
// Safe handling HTML
$code = htmlspecialchars($code);
// Process it first PHP Label
$code = preg_replace('/<\?php/', '<span style="color: purple;"><?php</span>', $code);
// Apply grammar highlighting
return nl2br(preg_replace_callback_array($patterns, $code));
}
// Output highlighted HTML Code
echo highlight_php_code($code);
?>
After this code is executed, a string in HTML format will be output, containing the styled PHP code:
Keywords turn blue and thick
The string turns green
The comment is grey italic
The variable is dark orange
You can embed it directly into your page, such as:
<pre style="background-color: #f9f9f9; padding: 10px;">
<?php echo highlight_php_code($code); ?>
</pre>
If you are developing a code sharing platform, for example:
https://m66.net/snippet/123
You can use this function to highlight the user's PHP code snippets in the View Code Details page to improve readability.
Use preg_replace_callback_array() to achieve PHP syntax highlighting, which is not only clear in logic, but also has good performance, suitable for lightweight code display needs. Of course, if you need more advanced syntax analysis capabilities, consider combining PHP's tokenizer extension or using third-party libraries (such as highlight.php).