Use highlight_string() when you need to produces HTML-formatted syntax highlighting for PHP source code in a PHP application. The examples below show the actual operation and its limitations.
What Is highlight_string() in PHP?
Produces HTML-formatted syntax highlighting for PHP source code. The exact signature supported by your installation depends on its PHP version and enabled extensions.
Its syntax is:
highlight_string(string $string, bool $return = ...): string|true
Parameters and return value: The parameter types, optional arguments, references, and return type are shown in the signature above. Optional parameters are marked with an ellipsis in this reference signature.
Example 1: Basic Usage
<?php
$highlighted = highlight_string("<?php echo 1;",true); echo strpos($highlighted,"<span") !== false ? "Highlighted" : "Plain";
Output:
Highlighted
Example 2: Different Input or Behavior
<?php
echo is_string(highlight_string("<?php echo 2;",true)) ? "HTML returned" : "Failed";
Output:
HTML returned
Practical Example: Applying the Function
<?php
$sourceCode = "<?php echo 42;"; $highlighted = highlight_string($sourceCode,true); echo strlen($highlighted) . " bytes of HTML";
Output:
208 bytes of HTML
Important Behavior and Edge Cases
Never run or evaluate untrusted code; highlighting generates HTML that must be handled as markup intentionally.
Comparison With Related Functions
| Approach | Difference |
|---|---|
highlight_string() | Produces HTML-formatted syntax highlighting for PHP source code. |
| Related operation | highlight_file() highlights a file; highlight_string() highlights an in-memory source string. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Ignoring the function-specific limitation | Never run or evaluate untrusted code; highlighting generates HTML that must be handled as markup intentionally. |
| Confusing this function with a related operation | highlight_file() highlights a file; highlight_string() highlights an in-memory source string. |
Key Takeaways
- Produces HTML-formatted syntax highlighting for PHP source code.
- Never run or evaluate untrusted code; highlighting generates HTML that must be handled as markup intentionally.
- highlight_file() highlights a file; highlight_string() highlights an in-memory source string.
Use highlight_string() for the specific operation demonstrated above. Check its prerequisites and handle failure conditions before using it with production data.