所以,我知道SO上有很多相关的问题,但它们都不是我想要的.我正在尝试实现一个PHP函数,它将文本URL从用户生成的帖子转换为链接.我正在使用来自Daring Fireball的"改进"正则表达式到页面底部:http://daringfireball.net/2010/07/improved_regex_for_matching_urls 该函数不返回任何内容,我不知道为什么.
<?php
if ( false === function_exists('linkify') ):
function linkify($str) {
$pattern = '(?xi)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'".,<>?«»“”‘’]))';
return preg_replace($pattern, "<a href=\"\\0\" rel=\"nofollow\" target=\"_blank\">\\0</a>", $str);
}
endif;
?>
Run Code Online (Sandbox Code Playgroud)
有人可以帮助我让这个工作吗?谢谢!
d_i*_*ble 11
试试这个:
$pattern = '(?xi)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`\!()\[\]{};:\'".,<>?«»“”‘’]))';
return preg_replace("!$pattern!i", "<a href=\"\\0\" rel=\"nofollow\" target=\"_blank\">\\0</a>", $str);
Run Code Online (Sandbox Code Playgroud)
PHP的preg功能确实需要分隔符.将i在年底使得它不区分大小写
如果你#用作分隔符,你就不需要!在模式中使用原始模式字符串(模式没有#):"#$pattern#i"
要确保链接正确,请执行以下操作:
$pattern = '(?xi)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'".,<>?«»“”‘’]))';
return preg_replace_callback("#$pattern#i", function($matches) {
$input = $matches[0];
$url = preg_match('!^https?://!i', $input) ? $input : "http://$input";
return '<a href="' . $url . '" rel="nofollow" target="_blank">' . "$input</a>";
}, $str);
Run Code Online (Sandbox Code Playgroud)
现在将附加http://到URL,以便浏览器不认为它是相对链接.
| 归档时间: |
|
| 查看次数: |
2586 次 |
| 最近记录: |