Alex
Alex

Reputation: 897

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

Upvotes: 34

Views: 33084

Answers (11)

Ledilson Motta
Ledilson Motta

Reputation: 73

Simple like that:

$text = "Atenção, isto é um link de teste";
$text = str_replace(
  [' ', ',', '&', '&', 'á', 'ã', 'à', 'é', 'ê', 'í', 'ç', 'õ', 'ô', 'ó', 'ú', "'", ")", "(", "]", "["],
  ['-', '', '', '', 'a', 'a', 'a', 'e', 'e', 'i', 'c', 'o', 'o', 'o', 'u', '', "", "", "", ""],
  $text
);

echo strtolower($text);

If you need more chars, add them in the str_replace.

Upvotes: 0

vstelmakh
vstelmakh

Reputation: 782

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>.'

Upvotes: 3

Cal
Cal

Reputation: 7157

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

Upvotes: 21

Sam Lee
Sam Lee

Reputation: 21

I found this code at http://code.seebz.net/p/autolink-php/ and tweaked it a bit to recognize www.* as links. I am not very conversant with regular expressions but I think the two str_replace lines can be modified to one regexp

<?php
$text = 'First link is: www.example.com. Second link is http://example.com. Third link is https://example.com. Fourth link is http://www.example.com. Fifth link is <a href="http://www.example.com">www.example.com</a>';

function autolink($str, $attributes=array()) {
$str = str_replace("http://www","www",$str);
$str = str_replace("https://www","www",$str);

$attrs = '';
foreach ($attributes as $attribute => $value) {
$attrs .= " {$attribute}=\"{$value}\"";
}
$str = ' ' . $str;
$str = preg_replace(
'`([^"=\'>])((http|https|ftp)://[^\s<]+[^\s<\.)])`i',
'$1<a href="$2"'.$attrs.'>$2</a>',
$str
);
$str = preg_replace(
'`([^"=\'>])((www).[^\s<]+[^\s<\.)])`i',
'$1<a href="http://$2"'.$attrs.'>$2</a>',
$str
);
$str = substr($str, 1);
return $str;
}

echo autolink($text);
?>

Upvotes: 2

Ben
Ben

Reputation: 68658

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)

Upvotes: 63

Arnold Daniels
Arnold Daniels

Reputation: 16583

Checkout my linkify function, which uses preg_replace_callback (PHP 5.3 only). It supports http, email and twitter:

http://www.jasny.net/articles/linkify-turning-urls-into-clickable-links-in-php/

/**
* Turn all URLs in clickable links.
*
* @param string $value
* @param array $protocols http/https, ftp, mail, twitter
* @param array $attributes
* @param string $mode normal or all
* @return string
*/
    function linkify($value, $protocols = array('http', 'mail'), array $attributes = array(), $mode = 'normal')
    {
        // Link attributes
        $attr = '';
        foreach ($attributes as $key => $val) {
            $attr = ' ' . $key . '="' . htmlentities($val) . '"';
        }

        $links = array();

        // Extract existing links and tags
        $value = preg_replace_callback('~(<a .*?>.*?</a>|<.*?>)~i', function ($match) use (&$links) { return '<' . array_push($links, $match[1]) . '>'; }, $value);

        // Extract text links for each protocol
        foreach ((array)$protocols as $protocol) {
            switch ($protocol) {
                case 'http':
                case 'https': $value = preg_replace_callback($mode != 'all' ? '~(?:(https?)://([^\s<]+)|(www\.[^\s<]+?\.[^\s<]+))(?<![\.,:])~i' : '~([^\s<]+\.[^\s<]+)(?<![\.,:])~i', function ($match) use ($protocol, &$links, $attr) { if ($match[1]) $protocol = $match[1]; $link = $match[2] ?: $match[3]; return '<' . array_push($links, '<a' . $attr . ' href="' . $protocol . '://' . $link . '">' . $link . '</a>') . '>'; }, $value); break;
                case 'mail': $value = preg_replace_callback('~([^\s<]+?@[^\s<]+?\.[^\s<]+)(?<![\.,:])~', function ($match) use (&$links, $attr) { return '<' . array_push($links, '<a' . $attr . ' href="mailto:' . $match[1] . '">' . $match[1] . '</a>') . '>'; }, $value); break;
                case 'twitter': $value = preg_replace_callback('~(?<!\w)[@#](\w++)~', function ($match) use (&$links, $attr) { return '<' . array_push($links, '<a' . $attr . ' href="https://twitter.com/' . ($match[0][0] == '@' ? '' : 'search/%23') . $match[1] . '">' . $match[0] . '</a>') . '>'; }, $value); break;
                default: $value = preg_replace_callback($mode != 'all' ? '~' . preg_quote($protocol, '~') . '://([^\s<]+?)(?<![\.,:])~i' : '~([^\s<]+)(?<![\.,:])~i', function ($match) use ($protocol, &$links, $attr) { return '<' . array_push($links, '<a' . $attr . ' href="' . $protocol . '://' . $match[1] . '">' . $match[1] . '</a>') . '>'; }, $value); break;
            }
        }

        // Insert all link
        return preg_replace_callback('/<(\d+)>/', function ($match) use (&$links) { return $links[$match[1] - 1]; }, $value);
    }

Upvotes: 1

ridgerunner
ridgerunner

Reputation: 34435

Correctly linkifying a URL is non-trivial. (See: http://www.codinghorror.com/blog/2008/10/the-problem-with-urls.html for more on why this is so.) I spent quite a bit of time on this and have come up with a pretty good solution to the problem (for both PHP and/or Javascript). See: http://jmrware.com/articles/2010/linkifyurl/linkify.html

Upvotes: 1

Hannan Gigih Prastawa
Hannan Gigih Prastawa

Reputation: 21

Try this...

<?

   function link_it($text)  
   {  
        $text= preg_replace("/(^|[\n ])([\w]*?)([\w]*?:\/\/[\w]+[^ \,\"\n\r\t<]*)/is", "$1$2<a href=\"$3\" >$3</a>", $text);  
        $text= preg_replace("/(^|[\n ])([\w]*?)((www)\.[^ \,\"\t\n\r<]*)/is", "$1$2<a href=\"http://$3\" >$3</a>", $text);
                $text= preg_replace("/(^|[\n ])([\w]*?)((ftp)\.[^ \,\"\t\n\r<]*)/is", "$1$2<a href=\"ftp://$3\" >$3</a>", $text);  
        $text= preg_replace("/(^|[\n ])([a-z0-9&\-_\.]+?)@([\w\-]+\.([\w\-\.]+)+)/i", "$1<a href=\"mailto:$2@$3\">$2@$3</a>", $text);  
        return($text);  
    }


$text = "ini link gue: http://sapua.com <br>
https://sapua.com <br>
anything1://www.sss.com <br>

dua www.google.com <br>
tiga http://www.google.com <br>

ftp.sapua.com <br>

[email protected]


";

print link_it($text);

?>

Upvotes: 2

Andrew
Andrew

Reputation: 10043

I found an example which allows for links that include ftp, https and others which seems to work fine for multiple URLs

how-to-detect-urls-in-text-and-convert-to-html-links-php-using-regular-expressions

<?php
// The Regular Expression filter
$pattern = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

//example text
$text="Example user text with a URL http://www.zero7web.com , second link http://www.didsburydesign.co.uk";

// convert URLs into Links
$text= preg_replace($pattern, "<a href=\"\\0\" rel=\"nofollow\">\\0</a>", $text);

echo $text;
?>

Proabably a good idea to add nofollow to the link too is it's a user submitted value.

Upvotes: 2

Bouke
Bouke

Reputation: 12198

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);

Upvotes: 7

Rik Heywood
Rik Heywood

Reputation: 13972

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);

Upvotes: 2

Related Questions