使用 Perl 正则表达式去除关闭 php 标签

发布于 2024-12-07 11:09:56 字数 397 浏览 0 评论 0原文

我有 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 技术交流群。

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

发布评论

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

评论(2

只有影子陪我不离不弃 2024-12-14 11:09:56

我现在有机会测试一下。读取所有文件确实有效。这个 Perl 代码对我有用:

local $/;
open FH, "<", "tmp.php";
$var = <FH>;
print "$var\n\n";
close FH;
$var =~ s/(\s*\?>\s*)$//s;
print "$var\n";

在以下 php 代码上:

<?php
//some code
?>
<?php
//some other code
?>

I now had a chance to test it. Reading all file does work. This perl code worked for me:

local $/;
open FH, "<", "tmp.php";
$var = <FH>;
print "$var\n\n";
close FH;
$var =~ s/(\s*\?>\s*)$//s;
print "$var\n";

on the following php code:

<?php
//some code
?>
<?php
//some other code
?>
兮子 2024-12-14 11:09:56

好吧,让我们来分解一下。

您想要匹配 '?>',因此我们将从 ('?>') 开始,但由于 '?'在正则表达式中具有特殊含义,我们需要对其进行转义:('\?>')

我们不关心结束标签之前的内容,但我们想确保它之后没有任何内容(除了空格)。你已经赚了很多钱了:我们需要 \s$。我会这样做:

('\?>')\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:

('\?>')\s*$

Hope that works for you.

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