简体   繁体   English

如何使用 php 链接字符串中的 url?

[英]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 " “在http://www.google.com查看

The original string can have more than 1 URL string.原始字符串可以有 1 个以上的 URL 字符串。

How do I do this in php?我如何在 php 中做到这一点?

Thanks谢谢

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) PHP 版本 < 5.3 (ereg_replace) 否则 (preg_replace)

lib_autolink does a pretty good job, avoiding pitfalls like extra punctuation after the link and links inside HTML tags: lib_autolink做得很好,避免了链接和 HTML 标签内的链接之后的额外标点符号等陷阱:

https://github.com/iamcal/lib_autolink https://github.com/iamcal/lib_autolink

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

Small update from nowadays.从今天开始的小更新。 Just a regex won't be enough.仅仅一个正则表达式是不够的。 Urls could contain unicode characters, brackets, punctuation etc. Urls 可以包含 unicode 字符、括号、标点符号等。

There is a Url highlight library that cover lots of edge cases.有一个Url 高亮库,涵盖了许多边缘情况。

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

I found an example which allows for links that include ftp, https and others which seems to work fine for multiple URLs我找到了一个示例,它允许包含 ftp、https 和其他似乎适用于多个 URL 的链接

how-to-detect-urls-in-text-and-convert-to-html-links-php-using-regular-expressions 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.将 nofollow 添加到链接可能也是一个好主意,因为它是用户提交的值。

I found this code at http://code.seebz.net/p/autolink-php/ and tweaked it a bit to recognize www.* as links.我在http://code.seebz.net/p/autolink-php/找到了这段代码,并对其进行了一些调整以将 www.* 识别为链接。 I am not very conversant with regular expressions but I think the two str_replace lines can be modified to one regexp我不是很熟悉正则表达式,但我认为两行 str_replace 可以修改为一个正则表达式

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

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>

someone@sapua.com


";

print link_it($text);

?>

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

Correctly linkifying a URL is non-trivial.正确链接 URL 并非易事。 (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). (请参阅: http : //www.codinghorror.com/blog/2008/10/the-problem-with-urls.html了解更多关于为什么会这样的信息。)我花了很多时间在这上面并提出了有一个很好的问题解决方案(对于 PHP 和/或 Javascript)。 See: http://jmrware.com/articles/2010/linkifyurl/linkify.html见: http : //jmrware.com/articles/2010/linkifyurl/linkify.html

Checkout my linkify function, which uses preg_replace_callback (PHP 5.3 only).查看我的 linkify 函数,它使用 preg_replace_callback(仅限 PHP 5.3)。 It supports http, email and twitter:它支持 http、email 和 twitter:

http://www.jasny.net/articles/linkify-turning-urls-into-clickable-links-in-php/ 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);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM