使用 Perl 正则表达式去除关闭 php 标签
我有 php 文件,我想删除结束标记 (?>),但前提是它是最后一个结束标记并且后面没有任何内容。
<?php
//some code
?>
<?php
//some other code
?> // <- this and only this should be removed
我尝试过模式 's/(\s*\?>\s*)$//s' 及其几个突变,但没有成功:它们删除了所有出现的 ?> ,破坏了代码,并且我不知道如何匹配EOF。
(是的,我知道一个解决方法:使用例如 tail -1
仅检查文件的最后一行,但这会使我的整个代码格式化脚本变得复杂,因此如果可以使用正确构造的正则表达式来解决问题,那就太好了。)
I have php file, and I want to remove closing tag (?>), but only if it is last closing tag and there is nothing after.
<?php
//some code
?>
<?php
//some other code
?> // <- this and only this should be removed
I have tried pattern 's/(\s*\?>\s*)$//s' and several of its mutations, but with no success: they remove all occurrences of ?>, breaking the code, and I don't know how to match EOF.
(Yes, I know a workaround: using e.g. tail -1
to check only last line of file, but it would complicate my whole code-formatting script, so if the problem can be resolved with properly constructed regex, it would be great.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我现在有机会测试一下。读取所有文件确实有效。这个 Perl 代码对我有用:
在以下 php 代码上:
I now had a chance to test it. Reading all file does work. This perl code worked for me:
on the following php code:
好吧,让我们来分解一下。
您想要匹配 '?>',因此我们将从
('?>')
开始,但由于 '?'在正则表达式中具有特殊含义,我们需要对其进行转义:('\?>')
。我们不关心结束标签之前的内容,但我们想确保它之后没有任何内容(除了空格)。你已经赚了很多钱了:我们需要
\s
和$
。我会这样做:希望这对你有用。
OK, let's break this down.
You want to match '?>', so we'll start with
('?>')
, but since '?' has special meaning in regex, we need to escape it:('\?>')
.We don't care about what's before the closing tag, but we want to make sure nothing (except whitespace) is after it. You were pretty much on the money with this: we need
\s
and$
. I'd do it like this:Hope that works for you.