How can PHP's preg_replace_callback() function be effectively used in combination with highlight_string() for syntax highlighting?
To effectively use PHP's preg_replace_callback() function in combination with highlight_string() for syntax highlighting, you can create a callback function that dynamically applies syntax highlighting to the matched text using HTML tags. This allows you to customize the highlighting style and colors based on the syntax of the code.
<?php
// Define the callback function for preg_replace_callback
function highlight_syntax($matches) {
// Apply syntax highlighting using HTML tags
return '<span style="color: blue;">' . $matches[0] . '</span>';
}
// Sample code snippet to highlight
$code = '<?php echo "Hello, World!"; ?>';
// Apply syntax highlighting using preg_replace_callback and highlight_string
$highlighted_code = highlight_string($code, true);
$highlighted_code = preg_replace_callback('/&lt;\?php(.*?)\?&gt;/s', 'highlight_syntax', $highlighted_code);
echo $highlighted_code;
?>