tags:

views:

85

answers:

5

Need Some Help With Regex:

I want to replace

[url=http://youtube.com]YouTube.com[/url]

with

<a href="http://youtube.com"&gt;YouTube.com&lt;/a&gt;

the regex

preg_replace("/[url=(.*?)](.*?)[/url]/is", '<a href="$1">$2</a>', $text);

why does this give me:

Warning: preg_replace() [function.preg-replace]: Unknown modifier 'r' in C:\Programa\wamp\www\func.php on line 18

+1  A: 

PHP is interpreting the '/' in /url as being the end of the regex and the start of the regex options. Insert a '\' before it to make it a literal '/'.

You need to escape the '['s in the same way (otherwise they will be interpreted as introducing a character class).

preg_replace("/\[url=(.*?)](.*?)\[\/url]/is", '<a href="$1">$2</a>', $text);
Dave Hinton
Like: \[url=(.*?)\](.*?)\[\/url\]
David Kemp
+6  A: 

You should escape special characters in your regular expression:

preg_replace('/\[url=(.*?)](.*?)\[\/url]/is', '<a href="$1">$2</a>', $text);

I have escaped the [ characters (they specify the start of a character class) and the / character (it specifies the boundaries of the regular expression.)

Alternatively (for the / character) you can use another boundary character:

preg_replace('#\[url=(.*?)](.*?)\[/url]#is', '<a href="$1">$2</a>', $text);

You still have to escape the [ characters, though.

Blixt
A: 

Both the slashes and square brackets are special characters in regex, you will need to escape them:

\/ \[ \]
Andre Miller
A: 

The 2nd '/' in a regex string ends the regex. You need to escape it. Also, preg_replace will interpret the '[url=(.*?)]' as a character class, so you need to escape those as well.

preg_replace('/\[url=(.*?)\](.*?)\[\/url\]/is', '<a href="$1">$2</a>', $text);
outis
A: 

You seem to be just starting out with regular expressions. If that is the case - or maybe even if it isn't - you will find the Regex Coach to be a very helpful tool. It provides a sandbox for us to test our pattern matches and our replace strings too. If you had been using that it would have highlighted the need to escape the special characters.

APC
looks nice thanks