简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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