Linkify Regex函数PHP大胆的火球方法 [英] Linkify Regex Function PHP Daring Fireball Method

查看:71
本文介绍了Linkify Regex函数PHP大胆的火球方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我知道有大量与SO相关的问题,但这些问题都不是我所寻找的.我正在尝试实现一个PHP函数,该函数会将用户生成的帖子中的文本URL转换为链接.我正在使用从Daring Fireball到页面底部的改进的"正则表达式: http://daringfireball. net/2010/07/improved_regex_for_matching_urls 该函数不返回任何内容,我不确定为什么.

So, I know there are a ton of related questions on SO, but none of them are quite what I'm looking for. I'm trying to implement a PHP function that will convert text URLs from a user-generated post into links. I'm using the 'improved' Regex from Daring Fireball towards the bottom of the page: http://daringfireball.net/2010/07/improved_regex_for_matching_urls The function does not return anything, and I'm not sure why.

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

有人可以帮我解决这个问题吗? 谢谢!

Can someone please help me get this to work? Thanks!

推荐答案

尝试一下:

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

PHP的preg函数确实需要定界符.最后的i使其不区分大小写

PHP's preg function do need delimiters. The i at the end makes it case-insensitive

如果使用#作为定界符,则无需在模式中转义!,因此使用原始模式字符串(该模式没有#):"#$pattern#i"

If you use # as the delimiter, you wan't need to escape the ! in the pattern as such use the original pattern string (the pattern does not have a #): "#$pattern#i"

要确保链接正确无误,请执行以下操作:

To ensure that the links are correct, do this:

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

这现在会将http://附加到网址中,以使浏览器不认为它是相对链接.

This will now append http:// to the urls so that browser doesn't think it is a relative link.

这篇关于Linkify Regex函数PHP大胆的火球方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆