views:

382

answers:

5

Ok so I have this regex that I created and it works fine in RegexBuddy but not when I load it into php. Below is an example of it.

Using RegexBuddy I can get it to works with this:

\[code\](.*)\[/code\]

And checking the dot matches newline, I added the case insensitive, but it works that way as well.

Here is the php:

$q = "[code]<div>html code to display on screen</div>[/code]";

$pattern = '/\[code\](.*)\[/code\]/si';

$m = preg_match($pattern, $q, $code);

So you can see I am using [code][/code] and then once I can extract this I will run htmlentities() on it to display instead of render html code.

+1  A: 

You're including the forward slash in the middle of your pattern (/code). Either escape it or delimit your pattern with something else (I prefer !).

cletus
+2  A: 

It's because you didn't escape the closing marker /

Escaping the backslashes wouldn't hurt either:

$pattern = "/\\[code\\](.*)\\[\\/code\\]/si";

PHP lets you choose any characters as the RegEx delimiter, so I'll often use a character which isn't also used in the regex, like @.

$pattern = "@\\[code\\](.*)\\[/code\\]@si";
nickf
A: 

You need to escape the forward slash in /code

$pattern = '/\[code\](.*)\[\/code\]/si';

Also, realize the matches are stored in $code, not $m

Edit: Beaten to it :p

Mike B
yup $m was just part of debug to know if it was true or false
A: 

This worked:

$pattern = '/\[code\](.*)\[\/code\]/si';
A: 

When transferring your regular expression from RegexBuddy to PHP, either generate a source code snippet on the Use tab, or click the Copy button on the toolbar at the top, and select to copy as a PHP preg string. Then RegexBuddy will automatically add the delimiters and flags that PHP needs, without leaving anything unescaped.

Jan Goyvaerts