SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Zealot
    Join Date
    May 2003
    Location
    somewhere on the Earth
    Posts
    113
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    regular expression help

    using regular expression to convert url to hyperlink

    code as following
    <?php
    $url=' http://sourceforge.net/tracker/?group_id=9028&atid=359028<br/>';

    // <br/> is not part of the link

    echo ereg_replace(
    "(http|https|ftp)://([[:alnum:]/+-=%&:_.~?]+[#[:alnum:]+]*)",
    "<a href='\\0'>\\0</a>",
    $url);

    ?>

    it will result :

    <a href='http://sourceforge.net/tracker/?group_id=9028&atid=359028<br/'>http://sourceforge.net/tracker/?group_id=9028&atid=359028<br/</a>

    note the extra <br/

    how could I get it work correctly?
    thanks in advance

  2. #2
    Chessplayer kleineme's Avatar
    Join Date
    Apr 2004
    Location
    Germany
    Posts
    608
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi,

    I don't know the syntax of the ereg functions, but maybe the preg expression will help you as well:

    Code:
    $url=' http://sourceforge.net/tracker/?group_id=9028&atid=359028<br/>';
    
    $regex = '#(?:https?|ftp)://[-a-zA-Z0-9]+(?:\.[-a-zA-Z0-9]+)*\.[a-zA-Z]{2,4}(?:/[-a-zA-Z0-9_:\@&?=+,.!/~*\'%\$]*)?#';
    $erg = preg_match_all($regex, $url, $m);
    echo nl2br(print_r($m, TRUE));
    
    $url = preg_replace($regex, '<a href="\0">\0</a>', $url);
    echo $url;
    Otherwise you may simply strip the <br/> off the string:

    Code:
    $url = str_replace("<br/>", "", $url);
    and then apply your regex to it.
    Never ascribe to malice,
    that which can be explained by incompetence.
    Your code should not look unmaintainable, just be that way.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •