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.

Need help with WordPress or WooCommerce?

Visit our Community Forums

Ask a Question

Recent Articles

From Our Community Forums

Blog Categories

Related Articles

If you enjoyed reading this, then please explore our other articles below:

Comments

Leave a comment
  1. Eugen May 19, 2020 at 10:09 pm - Reply

    This solution is limited to http(s) protocol and not working with urls containing non latin characters. Found a library to deal with this cases: https://github.com/vstelmakh/url-highlight

    • webroom May 20, 2020 at 7:45 am - Reply

      Great! Thanks for contributing to the topic! I’ve added it in the article as alternative solution.

Leave a Reply

Comment policy: We love comments and appreciate the time that readers spend to share ideas and give feedback. However, all comments are manually moderated and those deemed to be spam or solely promotional will be deleted.