-2

I have a string that I need to replace any url to be in <a> html tag

$str='Lorem Ipsum is simply dummy text of http://www.lipsum.com/ the printing';

$outputString=
'Lorem Ipsum is simply dummy text of <a href="http://www.lipsum.com">http://www.lipsum.com/</a> the printing';
Ibu
  • 42,752
  • 13
  • 76
  • 103
Husamuddin
  • 405
  • 1
  • 7
  • 19
  • The `$ouputString` is invalid, you need to escape the double quotes – AlexP Nov 22 '13 at 20:23
  • it's just a sample not exactly a real code, i just need tips for the answer – Husamuddin Nov 22 '13 at 20:25
  • 1
    @AlexP not if the string is surrounded by single quotes... as it is in the OP – OGHaza Nov 22 '13 at 20:25
  • This question has been asked so many times before on SO. Try searching around first. http://stackoverflow.com/questions/1188129/replace-urls-in-text-with-html-links/ and http://stackoverflow.com/questions/1959062/how-to-add-anchor-tag-to-a-url-from-text-input and http://stackoverflow.com/questions/1960461/convert-plain-text-urls-into-html-hyperlinks-in-php are just a few examples. – jszobody Nov 22 '13 at 20:27
  • 1
    -1 and vote for close This is a duplicate and you haven't even bothered to show you have made any effort to do this yourself. – Mike Brant Nov 22 '13 at 20:40
  • @OGHaza It was before the question was edited – AlexP Nov 22 '13 at 20:59
  • @AlexP whooops, apologies, my mistake. – OGHaza Nov 22 '13 at 21:01

1 Answers1

1
$str='Lorem Ipsum is simply dummy text of http://www.lipsum.com/ the printing';
$pattern='/\b((https?:\/\/|www.)[\w.\/-?=&#]+)(?=\s)/i';
$replace='<a href="$1">$1</a>';
echo preg_replace($pattern, $replace, $str);

Output:

Lorem Ipsum is simply dummy text of <a href="http://www.lipsum.com/">http://www.lipsum.com/</a> the printing'

Working on RegExr

OGHaza
  • 4,795
  • 7
  • 23
  • 29