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

标签 php regex string templates preg-replace

我正在将模板文件加载到字符串中以进行进一步处理(使用 file_get_contents)。该模板可能包含 PHP 代码,我需要在将重新格式化的模板内容发送到 stdout 之前将其删除。 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

关于php - 用于匹配(并删除)包含文件中的多行 PHP 代码的正则表达式模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32950217/

相关文章:

php - 使用 urlManager 在 url yii2 中隐藏一个 id

php - 全局 vs 函数 vs 静态类方法

php - 日期 ('Y-m-d H:i:s' ,$usr_profile->getCreatedAt()) 出现错误的问题?

javascript - 需要正则表达式

Java : how to get text between "http://" and first following "/" occurence ? 在第一次 "/"出现之后?

c++ - 在 C++ 中查找字符串中特殊字符的索引

php - Laravel 延迟加载

regex - 编辑捕获组值

javascript - 如何使用Javascript在给定句子中找到大写单词并在其前面添加一个字符?

string - UISearchBar textDidChange,searchtext 变量无法与 rangeOfString 一起使用?