PHP: How to find URLs in text (string) and display as links
Recently I was developing a custom solution for one of my client’s projects and I encountered a problem: A message (string) was stored in the database which may contain urls. I had to display that message and if it contains urls – it had to be display as active, clickable links. So here’s what worked for me:
PHP Snippet: Find URLs in string and make links using a function
$yourTextWithLinks = 'Here is an example for a text (string) that contains one or more url. Just visit http://www.google.com/ or <a href="http://www.google.com" rel="nofollow">http://google.com</a> and this is the end of the example.'; $text = strip_tags($yourTextWithLinks); function displayTextWithLinks($s) { return preg_replace('@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@', '<a href="$1">$1</a>', $s); } $text = displayTextWithLinks($text); echo $text;
Normally if you echo the variable $yourTextWithLinks it will display plain text with no active links. So now you can pass your string to the displayTextWithLinks() function and will return a text with clickable links in it.
If you’d like to use it without a function, here’s how.
PHP Snippet: Find URLs in text and make links without a function
$text = strip_tags($yourTextWithLinks); $textWithLinks = preg_replace('@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@', '<a href="$1" target="_blank" rel="nofollow">$1</a>', $text); echo $textWithLinks;
Learn more about:
Our reader Eugen found that the above solution is not working with urls containing non latin characters and found the following library:
Url highlight
Url highlight is a PHP library to parse URLs from string input. Works with complex URLs, edge cases and encoded input.
Url highlight features:
- Replace URLs in string by HTML tags (make clickable)
- Match URLs without scheme by top-level domain
- Work with HTML entities encoded input
- Extract URLs from string
- Check if string is URL
You can find the library in GitHub.
Related Articles
If you enjoyed reading this, then please explore our other articles below:
More Articles
If you enjoyed reading this, then please explore our other articles below: