简体   繁体   English

正则表达式HREF选择不完整

[英]Regular Expression HREF Selection Incomplete

This is a followup from another post at here . 这是此处另一篇文章的后续文章。

Problem: links aren't been wrapped with HREF completely, meaning just part of the URL is surrounded with link tags. 问题:链接没有完全用HREF包裹,这意味着URL的仅一部分被链接标记包围。 A function which detects links on a string. 检测字符串上的链接的函数。

If the string contains http://t.co/thions43 it's only returning part http://t.co/thi within a link tag. 如果字符串包含http://t.co/thions43则仅在链接标记内返回部分http://t.co/thi

<?php

function makeLink($match) {
    // Parse link.
     $substr = substr($match, 0, 6);
     if ($substr != 'http:/' && $substr != 'https:' && $substr != 'ftp://' && $substr != 'news:/' && $substr != 'file:/') {
        $url = 'http://' . $match;
     } else {
        $url = $match;
     }

     return '<a href="' . $url . '">' . $match . '</a>';
}
function makeHyperlinks($text) {
    // Find links and call the makeLink() function on them.
    return preg_replace('/((www\.|(http|https|ftp|news|file)+\:\/\/)[_.a-z0-9-]+\.[a-z0-9\/_:@=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])/e', "makeLink('$1')", $text);
}

?>

According to your comment, you have to make your regex case insensitive, also you can simplify : 根据您的评论,您必须使正则表达式不区分大小写,也可以简化:

return preg_replace('/((www\.|(http|https|ftp|news|file)+\:\/\/)[_.a-z0-9-]+\.[a-z0-9\/_:@=.+?,#%&~-]*[^.\'# !(?,><;\)])/ie', "makeLink('$1')", $text);

You could also use \\w instead of [a-zA-Z0-9_] and there're no needs for i flag: 您也可以使用\\w代替[a-zA-Z0-9_]并且不需要i标志:

'/((www\.|http|https|ftp|news|file):\/\/[\w.-]+\.[\w\/:@=.+?,#%&~-]*[^.\'"# !(?,><;\)])/e'

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

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