vstelmakh / url-highlight
Library to find URLs in text and turn them into clickable links
Requires
- php: ^8.4
- ext-mbstring: *
Requires (Dev)
- ext-intl: *
- friendsofphp/php-cs-fixer: ^3.95
- phpbench/phpbench: ^1.7
- phpstan/phpstan: ^2.2
- phpstan/phpstan-strict-rules: ^2.0
- phpunit/phpunit: ^13.3
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
URL Highlight – PHP library to find URLs in text and turn them into clickable links. Made to handle complex URLs, HTML markup and edge cases.
- Works with plain text, HTML and HTML entity encoded input.
- Matches URLs without a scheme by top-level domain, emails, IP hosts, Unicode and edge cases.
- Drops punctuation that belongs to the text, keeps what belongs to the URL.
- Leaves existing links and elements that may not contain anchors untouched.
- Renders links your way or returns URLs as parsed components.
Installation
Requires PHP 8.4+ with the mbstring extension.
Install the latest version with Composer:
composer require vstelmakh/url-highlight
On PHP below 8.4, use version ^3.2. It supports PHP 7.1 – 8.x but has a different API, see the
3.x readme.
Coming from 3.x? See Upgrade 3.x to 4.0.
Usage
UrlHighlight is the only entry point. It provides 2 methods:
highlight()to turn URLs into links.find()to get an array of URLs found in the text.
Highlight URLs
Pass your input text to highlight() and get it back with every URL replaced by a link. Everything else stays as it is.
<?php require __DIR__ . '/vendor/autoload.php'; use VStelmakh\UrlHighlight\UrlHighlight; $urlHighlight = new UrlHighlight(); echo $urlHighlight->highlight('Check the example.com website.'); // Output: // Check the <a href="http://example.com">example.com</a> website.
Two optional arguments control the result: $highlighter renders each URL, $format tells the library how to read
the input text.
Custom Highlighter
By default, each URL is simply wrapped in an anchor tag by SimpleHighlighter.
For any custom logic, you can use a CallbackHighlighter. To build the
link, use Anchor helper. It escapes the link text and attribute values for you.
The example below adds a nofollow attribute and uses the host as the link text:
<?php use VStelmakh\UrlHighlight\Highlighter\Anchor; use VStelmakh\UrlHighlight\Highlighter\CallbackHighlighter; use VStelmakh\UrlHighlight\Url; $highlighter = new CallbackHighlighter(function (Url $url): string { return Anchor::fromUrl($url) ->withText($url->host) ->withAttribute('rel', 'nofollow') ->render(); }); echo $urlHighlight->highlight('Visit http://example.com/path?q=hello today.', $highlighter); // Output: // Visit <a href="http://example.com/path?q=hello" rel="nofollow">example.com</a> today.
Anchor helper provides the next methods:
withText()sets the link text. The text is escaped.withHtml()sets markup inside the link, for example an icon. The HTML is not escaped.withAttribute()adds an attribute or replaces its value. Anullvalue renders the name only.render()returns the link as HTML.(string) $anchordoes the same.
A highlighter does not have to produce a link. The returned string replaces the URL, so it may be anything, for example
[redacted] for URLs pointing to an external host.
More examples:
Put HTML inside the link
<?php use VStelmakh\UrlHighlight\Highlighter\Anchor; use VStelmakh\UrlHighlight\Highlighter\CallbackHighlighter; use VStelmakh\UrlHighlight\Url; $highlighter = new CallbackHighlighter(function (Url $url): string { $html = sprintf( '<i class="icon-link"></i> %s', htmlspecialchars($url->host), ); return Anchor::fromUrl($url)->withHtml($html)->render(); }); echo $urlHighlight->highlight('Visit http://example.com/path?q=hello today.', $highlighter); // Output: // Visit <a href="http://example.com/path?q=hello"><i class="icon-link"></i> example.com</a> today.
Redact external URLs
<?php use VStelmakh\UrlHighlight\Highlighter\Anchor; use VStelmakh\UrlHighlight\Highlighter\CallbackHighlighter; use VStelmakh\UrlHighlight\Url; $highlighter = new CallbackHighlighter(function (Url $url): string { return $url->host === 'example.com' ? Anchor::fromUrl($url)->render() : '[redacted]'; }); echo $urlHighlight->highlight('Read example.com/docs, not other.org/spam.', $highlighter); // Output: // Read <a href="http://example.com/docs">example.com/docs</a>, not [redacted].
Tip
There is also the Highlighter interface. Implement it in a dedicated class for more complex logic. Such a highlighter is reusable and testable. See SimpleHighlighter for an example.
Important
The string a highlighter returns is written to the output as is. Escape every untrusted part of the HTML you
build yourself or pass to withHtml(). Anchor escapes attribute values but does not validate them, so do not set
attributes like href or onclick from untrusted input.
Input Format
The $format argument must describe the input text, otherwise URLs may not be highlighted correctly.
| Format | Text |
|---|---|
Format::Html (default) |
HTML markup. Tags and elements that may not hold a link are left untouched. |
Format::HtmlEncoded |
HTML markup with entity encoded text, e.g. the result of htmlspecialchars. |
Format::Plain |
Text without markup, taken as is. Angle brackets are ordinary characters. |
The default Format::Html fits text without markup as well. Use Format::Plain when angle brackets in the text must
stay ordinary characters, for example to match <user@example.com>.
A common case is user input that you escape before rendering. Set the format to Format::HtmlEncoded, so the escaped
text is processed correctly:
<?php use VStelmakh\UrlHighlight\Format; $encoded = htmlspecialchars('<b>http://example.com?a=1&b=2</b>'); echo $urlHighlight->highlight($encoded, format: Format::HtmlEncoded); // Output: // <b><a href="http://example.com?a=1&b=2">http://example.com?a=1&b=2</a></b>
Note
Format::HtmlEncoded matches against the decoded text, so the URL ends where it really ends, instead of running into
the markup that follows. It does more work internally than the other formats, so use it only for encoded text.
Find URLs
Pass your input text to find() and get the list of URLs it contains, each as a Url object with the
components parsed. Markup is ignored, the text is always processed as plain text.
<?php $urls = $urlHighlight->find('Visit example.com/path?a=1 today.'); $url = $urls[0]; $url->full; // 'example.com/path?a=1' $url->host; // 'example.com' $url->path; // '/path' $url->query; // '?a=1' $url->toHref(); // 'http://example.com/path?a=1' $url->isEmail(); // false
Tip
See Url for all available components and methods.
Contributing
Contributions are welcome. Please check out CONTRIBUTING.md for guidelines.
If you find this library useful, don't hesitate to give it a star! ⭐
Credits
Volodymyr Stelmakh
Licensed under the MIT License. See LICENSE for more information.