[英]How do I linkify urls in a string with php?
我有以下字符串:
"Look on http://www.google.com".
我需要將其轉換為:
原始字符串可以有 1 個以上的 URL 字符串。
我如何在 php 中做到這一點?
謝謝
您可以使用以下內容:
$string = "Look on http://www.google.com";
$string = preg_replace(
"~[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]~",
"<a href=\"\\0\">\\0</a>",
$string);
PHP 版本 < 5.3 (ereg_replace) 否則 (preg_replace)
lib_autolink
做得很好,避免了鏈接和 HTML 標簽內的鏈接之后的額外標點符號等陷阱:
從今天開始的小更新。 僅僅一個正則表達式是不夠的。 Urls 可以包含 unicode 字符、括號、標點符號等。
有一個Url 高亮庫,涵蓋了許多邊緣情況。
例子:
<?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>.'
我找到了一個示例,它允許包含 ftp、https 和其他似乎適用於多個 URL 的鏈接
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;
?>
將 nofollow 添加到鏈接可能也是一個好主意,因為它是用戶提交的值。
我在http://code.seebz.net/p/autolink-php/找到了這段代碼,並對其進行了一些調整以將 www.* 識別為鏈接。 我不是很熟悉正則表達式,但我認為兩行 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);
?>
嘗試這個...
<?
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);
?>
您將需要使用正則表達式...
這樣的事情會有所幫助。
$result = preg_replace('/\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[A-Z0-9+&@#\/%=~_|]/i', '<a href="\0">\0</a>', $text);
正確鏈接 URL 並非易事。 (請參閱: http : //www.codinghorror.com/blog/2008/10/the-problem-with-urls.html了解更多關於為什么會這樣的信息。)我花了很多時間在這上面並提出了有一個很好的問題解決方案(對於 PHP 和/或 Javascript)。 見: http : //jmrware.com/articles/2010/linkifyurl/linkify.html
查看我的 linkify 函數,它使用 preg_replace_callback(僅限 PHP 5.3)。 它支持 http、email 和 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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.