Page 1 of 1

Find and replace URL string

Posted: Thu Sep 09, 2010 8:27 pm
by worked
Hi there- I'm looking for a way to find a URL within a string and replace it with an a href tag including said URL. For instance, I've gotten the below to work, but it only accounts for "http" string, not ftp or https:

Code: Select all

$pattern = '((http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?)';
$string = 'This text needs to stay while the following URL needs to be wrapped in an a href tag: http://www.ohyeah.com';
$replacement = '<a href="">'.strstr($string, "http").'</a>';
echo preg_replace($pattern, $replacement, $string);
Is there a preg function that returns the pattern string only? I would use it in place of the strstr function within the $replacement var. Thanks any help is appreciated!

Re: Find and replace URL string

Posted: Thu Sep 09, 2010 10:41 pm
by requinix
It doesn't work because you're misunderstanding how preg_replace works. And how strstr works, but more testing would have shown that.

Assuming that the regular expression is correct, there's but one change to make:

Code: Select all

$replacement = '<a href="$0">$0</a>';

Re: Find and replace URL string

Posted: Fri Sep 10, 2010 6:38 am
by worked
Jeez, that was simple. Thanks again for your help!