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.
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With