简体   繁体   中英

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.

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

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.

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

这工作:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM