用于匹配(和删除)包含文件的多行 PHP 代码的正则表达式模式

Regexp pattern to match (and remove) multi-line PHP code from include files

我正在将模板文件加载到字符串中以供进一步处理(使用 file_get_contents)。此模板可能包含 PHP 代码,我需要在将重新格式化的模板内容发送到标准输出之前将其删除。 PHP 代码不应该被执行,它应该被删除。

示例:

<h1>This is a template. This is HTML code.</h1>
<?php
  // This is a PHP comment.
  uselessFunction ('foo', $bar);
  /* This is another PHP comment */
?>
<p>This is more HTML code followed by </p><?= outputUselessInfo ('Blah blah') ?>
<h1>More HTML</h1>
<? echo "foo " . $bar; ?>
<p>That's all, folks</p>

我需要删除所有 PHP 代码,留下:

<h1>This is a template. This is HTML code.</h1>
<p>This is more HTML code followed by 
<h1>More HTML</h1>
<p>That's all, folks</p>

什么正则表达式匹配所有 PHP 代码,单行或多行,长标签或短标签(例如,通过 preg_replace,将其删除,不留空行作为此操作的结果)?

我一直盯着自己看,但我看不到出路。根据 Google 我是第一个愚蠢到尝试这个的人,因为我还没有找到任何现成的模式。

(PS:我知道通常不鼓励在 PHP 中使用短标签;我只是想涵盖这种可能性。)

尝试以下正则表达式(替换为 ""):

/\n?<\?(php|=)?(.*?)\?>\n?/ms

解释:

\n?       - Tests for a newline
<         - Tests for start tag
\?        - Tests for '?' after the start tag 
(php|=)?  - Tests for the 'php' or '=' after the start tag
(.*?)     - Tests for any PHP code
\?        - Tests for end tag
\n?       - Tests for a newline
/ms        - Allows multiple lines

编辑: Fixed Multiline Support

或者试试这个

/(<[a-z].*?>.*?>)/gm

但它会删除所有 html。


O.k.,另一个try

/(<\?.*?\?>)/gms

现在应该在赋值之后了。