0

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.

Jan Goyvaerts
  • 21,379
  • 7
  • 60
  • 72
Joshua Fricke
  • 381
  • 3
  • 14

5 Answers5

2

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
  • 616,129
  • 168
  • 910
  • 942
2

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
  • 21,379
  • 7
  • 60
  • 72
1

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
  • 537,072
  • 198
  • 649
  • 721
0

This worked:

$pattern = '/\[code\](.*)\[\/code\]/si';
Joshua Fricke
  • 381
  • 3
  • 14
-1

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
  • 31,886
  • 13
  • 87
  • 111