This question has already been answered:

This code will make from the address http://example.ru/usr/about in the text a link in the following form <a href="http://example.ru/usr/about">example</a> . That is, the link leads to the correct resource but the description is not formed correctly. Minuses (-) and, perhaps, other characters are for some reason discarded. Help make the link look like the right kind

 $ctext = preg_replace( '/(http)+(s)?:(\/\/)((\w|\.)+)(\/)?(\S+)?/i', '<a target="_blank" rel="nofollow" href="\0">\4</a>', $ctext ); 

Here is the test code, not to be unfounded http://ideone.com/HGfnd

Reported as a duplicate by members of Visman , VenZell , aleksandr barakin , Bald , user194374 Jul. 22 at 5:55 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

    2 answers 2

     $link = 'сайт http://apokalipsis-2012.ru/?search=%20&test ну и так http://ya.ru далее'; $link = preg_replace('/http(s)?:\/\/[^\s]+/', '<a href="$0">$0</a>', $link); echo $link; 

    Or without http:

     $link = 'сайт http://apokalipsis-2012.ru/?search=%20&test ну и так http://ya.ru далее'; $link = preg_replace('/http(s)?:\/\/([^\s]+)/', '<a href="$0">$2</a>', $link); echo $link; 

    Added by

     $link = preg_replace('/http(s)?:\/\/([a-z0-9\-\.]+)[^\s]*/i', '<a href="$0">$2</a>', $link); 
    • But still not the same. ideone.com/80ZnN . The visible part of the link should be cut off from apokalipsis-2012.ru/?search=%20&test in atokalipsis-2012.ru - jfjgjkslxd
    • Added to the answer. - ling
     $ctext = preg_replace( '@(http)+(s)?:(\/\/)((\w|\.)+)(\/)?(\S+)? @i ', '<a target="_blank" rel="nofollow" href="\0">\4</a>', $ctext ); 
    • Alas. The check did not pass. The result is the same ideone.com/wL9ia - jfjgjkslxd