How do I linkify urls in a string with php?

2019-01-04 09:53发布

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

标签: php url string
9条回答
再贱就再见
2楼-- · 2019-01-04 10:13

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)

查看更多
做自己的国王
3楼-- · 2019-01-04 10:13

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);
查看更多
beautiful°
4楼-- · 2019-01-04 10:13

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);
查看更多
该账号已被封号
5楼-- · 2019-01-04 10:18

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);
    }
查看更多
地球回转人心会变
6楼-- · 2019-01-04 10:19

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);
?>
查看更多
Evening l夕情丶
7楼-- · 2019-01-04 10:28

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.

查看更多
登录 后发表回答