First of all, you need to escape—or even better, replace—the delimeters as explained in the other answers.
preg_replace('~((www|http://)[^ ]+)~', '<a href="\1">\1</a>', $str);
Secondly, to further improve the regex, the $n
replacement reference syntax is preferred over \\n
, as stated in the manual.
preg_replace('~((www|http://)[^ ]+)~', '<a href="$1">$1</a>', $str);
Thirdly, you are needlessly using capturing parentheses, which only slows things down. Get rid of them. Don't forget to update $1
to $0
. In case you are wondering, these are non-capturing parentheses: (?: )
.
preg_replace('~(?:www|http://)[^ ]+~', '<a href="$0">$0</a>', $str);
Finally, I would replace [^ ]+
with the shorter and more accurate \S
, which is the opposite of \s
. Note that [^ ]+
does not allow spaces, but accepts newlines and tabs! \S
does not.
preg_replace('~(?:www|http://)\S+~', '<a href="$0">$0</a>', $str);