Current Location: Home> Latest Articles> How to Customize the Output Style of the highlight_string Function for More Beautiful Syntax Highlighting?

How to Customize the Output Style of the highlight_string Function for More Beautiful Syntax Highlighting?

gitbox 2025-09-21
<span class="hljs-meta"><?php
// The example code in this article is written in PHP.
// highlight_string is a built-in PHP function for syntax highlighting PHP code.
// The default output comes with system styles in HTML, but often we need to customize the styles for a more visually pleasing design.
<p>// ------------------------------------------------------------</p>
<p># How to customize the output style of the highlight_string function for more beautiful syntax highlighting?<span></p>
<p>In PHP, the <code>highlight_string()

At this point, the $highlighted variable contains the highlighted HTML with tags.

2. Customizing the Color Scheme

The highlighting output depends on the highlight.comment, highlight.default, highlight.html, highlight.keyword, highlight.string, and other configuration options in php.ini. These can be modified at runtime using ini_set():

ini_set(&#039;highlight.comment&#039;, &#039;#999999; font-style: italic&#039;); 
ini_set(&#039;highlight.default&#039;, &#039;#333333&#039;); 
ini_set(&#039;highlight.html&#039;, &#039;#008000&#039;); 
ini_set(&#039;highlight.keyword&#039;, &#039;#0000FF; font-weight: bold&#039;); 
<span class="hljs-title function_ invoke__">ini_set(&#039;highlight.string&#039;, &#039;#DD1144&#039;);

This configuration makes comments appear gray and italic, keywords bold and blue, and strings red. By adjusting these values, you can achieve custom colors.

3. Wrapping the Highlighted Code in a Code Block

To integrate with the website's front-end style, we can wrap the highlighted result in

<span class="fun">
tags.

Then, define more intuitive code background and font styles in the CSS:

.code-block {
    class="hljs-attribute">background: #f7f7f7;
    padding: 10px;
    border-radius: 5px;
    overflow-x: auto;
    font-family: Consolas, Monaco, monospace;
}

4. Replacing Inline Styles

The HTML output from highlight_string() typically includes inline styles like style="color:...". If you want to use custom CSS, you can replace these inline styles with classes using regular expressions or DOM manipulation. For example:

$highlighted = preg_replace(
    &#039;/(.*?)<\/span>/&#039;,
    class="hljs-string">&#039;<span class="code-color-$1">$2</span>&#039;,
    $highlighted
);

This will replace the different colored tags with corresponding classes, which can then be managed with CSS.

Conclusion

By using the return value from highlight_string(), we can freely adjust the syntax highlighting of PHP code. Common methods include:

  1. Using ini_set() to configure the color scheme;

  2. Wrapping the highlighted output in

    tags;

  3. Replacing inline styles with custom CSS classes.