How to replace an url in a text

Discussion in 'PHP' started by gladikarthik, Jan 4, 2010.

  1. #1
    Hello Every one..
    i need regular expression to replace a url with link.

    consider
    $text=welcome to http://www.mysite.com continue with some content

    jst my need is

    $text=welcome to <a href="http://www.mysite.com">http://www.mysite.com</a> continue with some content...

    i tried

    $text=preg_replace('@(https?://([-\w\.]+)+:)\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@', '<a href="$1">$1</a>', $text);

    but it womits the url after a hypen(-) presents
    ex http://www.mysite.com/test-link will went to http://www.mysite.com/test

    help me in this issue,,, thanks
     
    gladikarthik, Jan 4, 2010 IP
  2. MyVodaFone

    MyVodaFone Well-Known Member

    Messages:
    1,048
    Likes Received:
    42
    Best Answers:
    10
    Trophy Points:
    195
    #2
    
    
    $text = "welcome to http://www.mysite.com continue with some content"; 
    
    $search = "/(http[s]*:\/\/[\S]+)/";
    $replace = "<a href='\${1}'>\${1}</a>";
    $output = preg_replace($search, $replace, $text)
    
    
    PHP:
     
    MyVodaFone, Jan 5, 2010 IP
  3. gladikarthik

    gladikarthik Peon

    Messages:
    5
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thank you..Its Working.....
     
    gladikarthik, Jan 5, 2010 IP