使用 php 正则表达式解析块
我正在尝试用 PHP 编写一个(我认为)非常简单的正则表达式,但它不起作用。 基本上我有一个这样定义的块:
%%%%blockname%%%%
stuff goes here
%%%%/blockname%%%%
我不擅长 RegEx,但这就是我尝试过的:
preg_match_all('/^%%%%(.*?)%%%%(.*?)%%%%\/(.*?)%%%%$/i',$input,$matches);
它返回一个包含 4 个空条目的数组。
我想除了实际工作之外,第三场比赛还需要某种指针,因为它应该等于第一场比赛?
请赐教:)
I'm trying to write a (I think) pretty simple RegEx with PHP but it's not working.
Basically I have a block defined like this:
%%%%blockname%%%%
stuff goes here
%%%%/blockname%%%%
I'm not any good at RegEx, but this is what I tried:
preg_match_all('/^%%%%(.*?)%%%%(.*?)%%%%\/(.*?)%%%%$/i',$input,$matches);
It returns an array with 4 empty entries.
I guess it also, apart from actually working, needs some sort of pointer for the third match because it should be equal to the first one?
Please enlighten me :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要允许点匹配换行符,并允许
^
和$
在行的开头和结尾处匹配(不仅仅是整个字符串): >s(单行)选项使点匹配任何字符,包括换行符。
m
(多行)选项允许^
和$
在行首和行尾匹配。正则表达式中不需要
i
选项,因为其中没有区分大小写的字符。然后,回答问题的第二部分:如果两种情况下的 blockname 相同,那么您可以通过使用对第一个捕获组的反向引用来明确这一点:
You need to allow the dot to match newlines, and to allow
^
and$
to match at the start and end of lines (not just the entire string):The
s
(single-line) option makes the dot match any character including newlines.The
m
(multi-line) option allows^
and$
to match at the start and end of lines.The
i
option is unnecessary in your regex since there are no case-sensitive characters in it.Then, to answer the second part of your question: If
blockname
is the same in both cases, then you can make that explicit by using a backreference to the first capturing group:我很确定你不能,因为这些操作需要保存变量,而你不能在正则表达式中保存。您应该尝试使用 PHP 的内置标记解析器来执行此操作。 http://php.net/manual/en/function.token-get -all.php
I'm pretty sure you can't since these operations would need to save a variable and you can't in regex. You should try to do this using PHP's built-in token parser. http://php.net/manual/en/function.token-get-all.php