0

I can;t figure out what's wrong with my line:

$ret = preg_replace( "(http://|https://|http://www.|https://www.)([[:alnum:]#?~/&=._-]+)", "<a href=\"\\1\\2\" target=\"_blank\">\\1\\2</a>", $ret);

I tried inserting a / in the first pos of the first arg but that didn't work.

I'm stumped. Thanks for any help.

1
  • ouch too many / use them as \/ u need to escape them Commented Apr 12, 2014 at 17:37

2 Answers 2

2

Just add delimiter to your regex, choose one that is not present in your expression to avoid escaping, here I suggest !:

$ret = preg_replace( "!(http://|https://|http://www.|https://www.)([[:alnum:]#?~/&=._-]+)!", "<a href=\"$1$2\" target=\"_blank\">$1$2</a>", $ret);

You could also simplify a bit:

$ret = preg_replace( "!(https?://(?:www\.)?[\w#?~/&=.-]+)!", "<a href=\"$1\" target=\"_blank\">$1</a>", $ret);
Sign up to request clarification or add additional context in comments.

Comments

0
$ret = preg_replace(
                '/((?:http:\/\/|https:\/\/)(?:www\.)?)([[:alnum:]#?~\/&=._-]+)/', 
                '<a href="$1$2" target="_blank">$1$2</a>', 
                $ret
);

It should work like this. Basically, you need to escape the forward slashes in your regex.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.