2

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

1
  • Your regex should work - but only if you read the entire file content into one variable - and then parse it. If you use something like perl -p -i -e 's/(\s*\?>\s*)$//' filename.php, then each line is processed one at a time. Obviously, this will strip all occurrences. Commented Sep 29, 2011 at 11:01

2 Answers 2

2

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
?>
Sign up to request clarification or add additional context in comments.

1 Comment

It works: perl -pi -w -0777 -e 's/(\s*\?>\s*)$/;/s' file.php (argument -0777 for one-liner causes reading file as one string). Additionally, I have found that replacing ?> by empty string may cause syntax errors e.g. for such line: `<?php echo 'a' ?>. Replacing with ';' is safe. Thanks everybody.
0

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.

1 Comment

\w is a word character, not whitespace. You want \s.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.