Understand the Backward Compatibility Promise
master9.x). Deprecations will be marked with @deprecated and will only be removed in the next major release.repository·master·Indexed 20 days ago
https://github.com/scrivo/highlight.phpA server-side PHP syntax highlighter that ports highlight.js functionality. It supports 185 languages with options for explicit language selection or automatic language detection. The library provides the Highlight\Highlighter class for processing code and Highlight\Language for managing language definitions, while maintaining compatibility with highlight.js stylesheets.
9.x). Deprecations will be marked with @deprecated and will only be removed in the next major release.The recommended way to install highlight.php is using Composer. It is recommended to use a caret version range (e.g., ^9.14) to allow for minor updates and bug fixes while adhering to the project's backward compatibility promise.
composer require scrivo/highlight.phpTo use highlight.php, instantiate the Highlight\Highlighter class. By default, the constructor automatically registers all bundled languages. If you want to manage language registration manually to save memory or improve performance, pass false to the constructor.
Available configuration options (via internal state) include:
classPrefix: The CSS class prefix applied to highlighted spans (defaults to hljs-).tabReplace: A string used to replace tab characters (defaults to null, meaning no replacement).useBR: Whether to use <br> tags (defaults to false).languages: The set of languages used for auto-detection.use Highlight\Highlighter;
// Automatically load all bundled languages
$highlighter = new Highlighter();
// Or, load languages manually for better performance
$highlighter = new Highlighter(false);You can use highlightAuto() to let the library detect the language.
Warning: Auto-detection is a brute-force process and can be extremely inefficient if you do not limit the search space. It is highly recommended to use setAutodetectLanguages() to provide a specific list of candidate languages to improve performance and accuracy.
$hl = new \Highlight\Highlighter();
// Limit detection to specific languages for performance and accuracy
$hl->setAutodetectLanguages(array('ruby', 'python', 'perl'));
$highlighted = $hl->highlightAuto(file_get_contents('some_ruby_script.rb'));
echo "<pre><code class=\"hljs {$highlighted->language}\">";
echo $highlighted->value;
echo "</code></pre>";In explicit mode, you specify the exact language you want to highlight. This is the most efficient and accurate method. The \Highlight\Highlighter class returns a result object containing the language name and the highlighted value (HTML). If an invalid language is provided, a DomainException is thrown.
// Instantiate the Highlighter.
$hl = new \Highlight\Highlighter();
$code = file_get_contents('some_ruby_script.rb');
try {
// Highlight some code.
$highlighted = $hl->highlight('ruby', $code);
echo "<pre><code class=\"hljs {$highlighted->language}\">";
echo $highlighted->value;
echo "</code></pre>";
}
catch (DomainException $e) {
// This is thrown if the specified language does not exist
echo "<pre><code";
echo htmlentities($code);
echo "</code></pre>";
}The project includes stylesheets compatible with highlight.js in the styles directory. You can use the HighlightUtilities namespace to programmatically locate these files or retrieve available themes.
Available functions in `\HighlightUtilities\`:
- `getAvailableStyleSheets(bool $filePaths = false): string[]`
- `getStyleSheet(string $name): false|string`
- `getStyleSheetFolder(): string`
- `getStyleSheetPath(string $name): string`
- `getLanguagesFolder(): string`
- `getLanguageDefinitionPath(string $name): string`
- `getThemeBackgroundColor(string $name): float[]`
- `splitCodeIntoArray(string $html): false|string[]`To use a specific language for highlighting, instantiate the Highlight\Language class by providing the language name and the file path to its JSON definition file. The class will load and decode the JSON content into a Mode object.
Note that the constructor throws an \InvalidArgumentException if the provided file path is inaccessible.
use Highlight\Language;
// $lang is the name of the language (e.g., 'php')
// $filePath is the path to the .json definition file
$language = new Language('php', '/path/to/languages/php.json');You can customize the output of the highlighter using the following methods:
setAutodetectLanguages(array $set): Defines which languages the highlightAuto() method should probe. Limiting this set improves performance.setTabReplace($tabReplace): Sets a string to replace characters in the source code.setClassPrefix($classPrefix): Sets the CSS class prefix (e.g., hljs-) applied to the generated <span> tags.enableSafeMode() / disableSafeMode(): Toggles safe mode. In safe mode, if an error occurs during highlighting, the library falls back to escaping the raw code instead of throwing an exception.$highlighter = new Highlighter();
$highlighter->setAutodetectLanguages(['php', 'javascript', 'json']);
$highlighter->setTabReplace(' '); // Use 4 spaces instead of tabs
$highlighter->setClassPrefix('code-');Use the highlightAuto() method when the language of the code is unknown. The method iterates through a subset of registered languages and returns the result with the highest relevance score.
Arguments:
$code (string): The raw code to highlight.$languageSubset (string[]|null, default null): An array of language names to limit the search. If null, it uses the languages defined in the highlighter's options (typically web development languages) or all registered languages.// Automatically find the best language match
$result = $highlighter->highlightAuto('function hello() { return "world"; }');
echo "Detected language: " . $result->language . "\n";
echo $result->value;Languages in highlight.php are stored statically, meaning they are shared across all instances of Highlighter.
Highlighter::registerAllLanguages(): Registers all 185+ bundled languages.Highlighter::registerLanguage($languageId, $filePath, $overwrite = false): Registers a specific language definition from a JSON file.Highlighter::listBundledLanguages(): Returns an array of all language IDs available in the library's distribution.Highlighter::listRegisteredLanguages($includeAliases = false): Returns an array of currently registered language IDs.Highlighter::clearAllLanguages(): Removes all registered languages.// Register a custom language definition
Highlight\Highlighter::registerLanguage('my_lang', '/path/to/my_lang.json');
// List what is currently available
$langs = Highlight\Highlighter::listRegisteredLanguages(true);The Language class implements __get() to allow direct access to properties defined in the underlying JSON Mode object. This provides a convenient way to access configuration like case_insensitive or other custom properties without manually traversing the mode object.
Note on Deprecations:
$language->mode is DEPRECATED. All properties traditionally inside of $mode are now available directly from the Language instance.case_insensitive instead of caseInsensitive to maintain compatibility with highlight.js requirements.After instantiating a Language object, you must call the compile() method to process the loaded JSON definition into a usable internal state (compiling regexes, keywords, and nested modes).
Since version 9.17.1.0, compile() accepts a $safeMode boolean parameter:
$safeMode is false (default behavior) and the language definition uses the self keyword at the top-level of its contains array, a \LogicException will be thrown.$safeMode is true, the self references at the top-level are filtered out instead of throwing an error.$language->compile(false);