How do I linkify urls in a string with php?

I have the following string:

"Look on http://www.google.com".

I need to convert it to:

"Look on http://www.google.com"

The original string can have more than 1 URL string.

How do I do this in php?

Thanks


Solution 1:

You can use the following:

$string = "Look on http://www.google.com";
$string = preg_replace(
              "~[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]~",
              "<a href=\"\\0\">\\0</a>", 
              $string);

PHP versions < 5.3 (ereg_replace) otherwise (preg_replace)

Solution 2:

lib_autolink does a pretty good job, avoiding pitfalls like extra punctuation after the link and links inside HTML tags:

https://github.com/iamcal/lib_autolink

Solution 3:

Have a look at regular expressions. You would then do something like:

$text = preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@', '<a href="$1">$1</a>', $text);

Solution 4:

Small update from nowadays. Just a regex won't be enough. Urls could contain unicode characters, brackets, punctuation etc.

There is a Url highlight library that cover lots of edge cases.

Example:

<?php

use VStelmakh\UrlHighlight\UrlHighlight;

$urlHighlight = new UrlHighlight();
$urlHighlight->highlightUrls('Look on http://www.google.com or even google.com.');
// return: 'Look on <a href="http://www.google.com">http://www.google.com</a> or even <a href="http://google.com">google.com</a>.'

Solution 5:

You will need to use regular expressions...

Something like this will help.

$result = preg_replace('/\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[A-Z0-9+&@#\/%=~_|]/i', '<a href="\0">\0</a>', $text);