Skip to content

highlight_string()

In this article, we will focus on the PHP highlight_string() function. We will provide you with an overview of the function, how it works, and examples of its use.

Introduction to the highlight_string() function

The highlight_string() function is a built-in function in PHP that is used to highlight the syntax of a string that contains PHP code. It can be used to display the syntax of a PHP string in a web page or to generate a formatted PHP string for documentation purposes.

The highlight_string() function takes a PHP string as its argument and generates an HTML representation of the string with syntax highlighting. It supports a single optional boolean parameter to control whether the highlighted HTML is echoed directly or returned as a string.

How to use the highlight_string() function

Using the highlight_string() function is very simple. You just need to call the function and pass the PHP string that you want to highlight. Here is an example:

How to use the highlight_string() function?

php
<?php
$string = '<‌?php echo "Hello, World!"; ?>';
highlight_string($string);
?>

In this example, we have a variable $string that contains a PHP string that we want to highlight. We then call the highlight_string() function and pass the string as an argument. The function generates an HTML representation of the PHP string with syntax highlighting and outputs it to the browser.

Customizing the output

The highlight_string() function has a simple signature: highlight_string(string $string, bool $return = false): string|void. By default, it outputs the highlighted HTML directly to the browser. If you set the second parameter to true, the function returns the HTML string instead of echoing it, allowing you to store or modify it before output.

Here is an example of how to use the return parameter:

Example of PHP highlight_string()

php
<?php
$string = '<‌?php echo "Hello, World!"; ?>';
$highlighted = highlight_string($string, true);
echo '<pre>' . $highlighted . '</pre>';
?>

Note that highlight_string() does not support custom CSS classes, line numbers, or short tag toggling. For advanced syntax highlighting with custom styling or line numbers, you would typically use the token_get_all() function to manually parse the code and apply your own CSS, or use a third-party library.

Conclusion

In conclusion, the highlight_string() function is a built-in tool for generating formatted PHP strings with syntax highlighting. By understanding how to use the function and its return parameter, you can take advantage of this feature to display readable, highlighted code in your web applications.

Practice

What is the primary function of the highlight_string() function in PHP?

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.