Strip closing php tag using perl regex
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.)
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
?>
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.
精彩评论