SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Zealot
    Join Date
    Dec 2010
    Posts
    118
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    regular expression covert url to link (unless already is a link)

    i wrote this code and i was having a problem since
    it will convert this:
    http://www.ccc.com
    to:
    <a target="_blank" rel="nofollow" href="http://www.ccc.com">http://www.ccc.com</a>
    but if there was already a link:
    <a href="http://www.xxx.com">http://www.xxx.com</a>
    it will change it like that:
    <a href="http://www.xxx.com<a href="http://www.xxx.com">http://www.xxx.com"></a></a>

    how can i make my code ignore the links?
    Code:
    function render_links($str){
    		return ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]","<a target=\"_blank\" rel=\"nofollow\" href=\"/go/\\0\">\\0</a>", $str);
    	}

  2. #2
    Keeper of the SFL StarLion's Avatar
    Join Date
    Feb 2006
    Location
    Atlanta, GA, USA
    Posts
    3,747
    Mentioned
    64 Post(s)
    Tagged
    0 Thread(s)
    preg (PS: EREG is deprecated.) does not have the logic built in to handle this in one line without some really awful and long patterns.

    Incidentally, your system will fail to pass variables, because & and ? are not in your parsing.

    Simple suggestion would be to replace all current links with a temporary value (Something like #http;//theurl# , though you should probably use a more obscure character than that. Note the semicolon instead of the colon), then do your replacement, then undo the temporary values.
    Never grow up. The instant you do, you lose all ability to imagine great things, for fear of reality crashing in.


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
  •