Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace http:// or www with <a href.. in PHP

I've created this regex

(www|http://)[^ ]+

that match every http://... or www.... but I dont know how to make preg_replace that would work, I've tried

preg_replace('/((www|http://)[^ ]+)/', '<a href="\1">\1</a>', $str);

but it doesn't work, the result is empty string.

like image 300
Jakub Arnold Avatar asked Jul 04 '09 21:07

Jakub Arnold


2 Answers

You need to escape the slashes in the regex because you are using slashes as the delimiter. You could also use another symbol as the delimiter.

// escaped
preg_replace('/((www|http:\/\/)[^ ]+)/', '<a href="\1">\1</a>', $str);

// another delimiter, '@'
preg_replace('@((www|http://)[^ ]+)@', '<a href="\1">\1</a>', $str);
like image 189
Paige Ruten Avatar answered Oct 23 '22 11:10

Paige Ruten


When using the regex codes provided by the other users, be sure to add the "i" flag to enable case-insensitivity, so it'll work with both HTTP:// and http://. For example, using chaos's code:

preg_replace('!(www|http://[^ ]+)!i', '<a href="\1">\1</a>', $str);
like image 2
zacharyliu Avatar answered Oct 23 '22 12:10

zacharyliu