-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';
7
  • The $ouputString is invalid, you need to escape the double quotes Commented Nov 22, 2013 at 20:23
  • it's just a sample not exactly a real code, i just need tips for the answer Commented Nov 22, 2013 at 20:25
  • 1
    @AlexP not if the string is surrounded by single quotes... as it is in the OP Commented Nov 22, 2013 at 20:25
  • This question has been asked so many times before on SO. Try searching around first. stackoverflow.com/questions/1188129/… and stackoverflow.com/questions/1959062/… and stackoverflow.com/questions/1960461/… are just a few examples. Commented Nov 22, 2013 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. Commented Nov 22, 2013 at 20:40

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

$1 means the first capture group in the match, which in this case is the URL.
the pattern doesn't match this link youtube.com/watch?v=J4TAWrT4upY and other links
Any character you need to match just add into the [...] in the middle. I'll add ?, =, # and & now.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.