preg_match 在 regexbuddy 中工作,而不在 php 中工作

发布于 2024-07-12 23:00:46 字数 485 浏览 6 评论 0原文

好的,我创建了这个正则表达式,它在 RegexBuddy 中工作正常,但当我将其加载到 php 中时却不行。 下面是一个例子。

使用 RegexBuddy 我可以让它与此一起工作:

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

检查点是否与换行符匹配,我添加了不区分大小写,但它也可以这样工作。

这是 php:

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

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

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

所以你可以看到我正在使用 [code][/code],然后一旦我可以提取它,我将在其上运行 htmlentities() 来显示而不是渲染 html 代码。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

掐死时间 2024-07-19 23:00:46

您在模式(/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 !).

甚是思念 2024-07-19 23:00:46

将正则表达式从 RegexBuddy 传输到 PHP 时,可以在“使用”选项卡上生成源代码片段,或者单击顶部工具栏上的“复制”按钮,然后选择复制为 PHP preg 字符串。 然后 RegexBuddy 将自动添加 PHP 所需的分隔符和标志,而不会留下任何未转义的内容。

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.

风流物 2024-07-19 23:00:46

这是因为您没有转义结束标记 /

转义反斜杠也不会造成伤害:

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

PHP 允许您选择任何字符作为 RegEx 分隔符,因此我经常使用不是的字符也用在正则表达式中,如@

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

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";
末蓝 2024-07-19 23:00:46

这有效:

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

This worked:

$pattern = '/\[code\](.*)\[\/code\]/si';
燃情 2024-07-19 23:00:46

您需要转义 /code 中的正斜杠

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

另外,要意识到匹配存储在 $code 中,而不是 $m

编辑:击败它:p

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文