PHP正则表达式和输入问题
代码
(preg_match_all("#\[level-(.+)-\](.+?)\[/level\]#", $string, $matches)
问题
如果我使用 Enter 为 $string
分配任何值,我的正则表达式将不起作用。
示例:
//This doesn't work
$string = '[level-0-]This is a
test[/level]';
//This works
$string = '[level-0-]This is a test[/level]';
我想要什么
我希望我的正则表达式能够工作,无论之间有什么字符(输入等)。
如果有人能帮助我解决这个问题,我会很高兴。我还没有深入研究正则表达式,所以我不太擅长它:(
Code
(preg_match_all("#\[level-(.+)-\](.+?)\[/level\]#", $string, $matches)
Problem
if I assign any value to $string
with enter, my regex doesn't work.
Example:
//This doesn't work
$string = '[level-0-]This is a
test[/level]';
//This works
$string = '[level-0-]This is a test[/level]';
What I Want
I would like my regex to work no matter what characters between (enter, etc..).
I will be glad if anyone could help me out with this one. I still didn't dig into regex yet so I'm not that good with it :(
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您只需要在正则表达式中添加 DOTALL 标志
/s
即可。这允许点.
匹配任何字符,包括换行符(默认情况下不这样做)。另请参阅 PCRE 标志列表 http://php.net/manual/en /reference.pcre.pattern.modifiers.php
You just need the DOTALL flag
/s
in your regex. This allows the dot.
to match any character, including linebreaks (which it doesn't do per default).See also the PCRE flags list http://php.net/manual/en/reference.pcre.pattern.modifiers.php
您可能需要通过将 /s 标志添加到您的模式中,让正则表达式将其输入视为单行。
You probably need to get regex to treat its input as a single line by adding the /s flag to your pattern.
使用
s
模式修饰符:如果设置此修饰符,模式中的点元字符将匹配所有字符,包括换行符。如果没有它,换行符将被排除。 (参考:正则表达式模式中可能的修饰符)
Use
s
Pattern Modifier:If this modifier is set, a dot metacharacter in the pattern matches all characters, including newlines. Without it, newlines are excluded. (Ref: Possible modifiers in regex patterns)
这应该有效:
this should work :
“Test[.|\n]is[.|\n]a[.|\n]test”
这可能有效"Test[.|\n]is[.|\n]a[.|\n]test"
this might work