mc.watras
mc.watras

Reputation: 381

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.)

Upvotes: 2

Views: 629

Answers (2)

Aleks G
Aleks G

Reputation: 57316

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
?>

Upvotes: 2

Tom Wright
Tom Wright

Reputation: 11479

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.

Upvotes: 0

Related Questions