Joshua Fricke
Joshua Fricke

Reputation: 391

preg_match works in regexbuddy, not in php

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.

Upvotes: 0

Views: 1012

Answers (5)

Jan Goyvaerts
Jan Goyvaerts

Reputation: 21999

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.

Upvotes: 2

Joshua Fricke
Joshua Fricke

Reputation: 391

This worked:

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

Upvotes: 0

Mike B
Mike B

Reputation: 32155

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

Upvotes: -1

nickf
nickf

Reputation: 546055

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";

Upvotes: 1

cletus
cletus

Reputation: 625087

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 !).

Upvotes: 2

Related Questions