Find and replace URL string

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
worked
Forum Newbie
Posts: 6
Joined: Sat May 08, 2010 6:40 pm

Find and replace URL string

Post 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!
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Find and replace URL string

Post 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>';
worked
Forum Newbie
Posts: 6
Joined: Sat May 08, 2010 6:40 pm

Re: Find and replace URL string

Post by worked »

Jeez, that was simple. Thanks again for your help!
Post Reply