我正在将模板文件加载到字符串中以进行进一步处理(使用 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
关于php - 用于匹配(并删除)包含文件中的多行 PHP 代码的正则表达式模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32950217/