php - 使用正则表达式提取 PHP 代码

标签 php regex

我想用正则表达式提取本节的整个 PHP 代码:

<h1>Extract the PHP Code</h1>
    <?php
        echo(date("F j, Y, g:i a") . ' and a stumbling block: ?>');
        /* Another stumbling block ?> */
        echo(' that works.');
    ?>
<p>Some HTML text ...</p>

不幸的是,我的正则表达式卡在了绊脚石上:

/<[?]php[^?>]*[?]>/gim

有人知道如何获取完整的 PHP 代码吗?

最佳答案

这样的事情可能会奏效

/<\?php.+?\?>$/ms

Regular expression visualization

此模式使用两个 flags

  • m 用于 PCRE_MULTILINE

    By default, PCRE treats the subject string as consisting of a single "line" of characters (even if it actually contains several newlines). The "start of line" metacharacter (^) matches only at the start of the string, while the "end of line" metacharacter ($) matches only at the end of the string, or before a terminating newline (unless D modifier is set). This is the same as Perl. When this modifier is set, the "start of line" and "end of line" constructs match immediately following or immediately before any newline in the subject string, respectively, as well as at the very start and end. This is equivalent to Perl's /m modifier. If there are no "\n" characters in a subject string, or no occurrences of ^ or $ in a pattern, setting this modifier has no effect.

  • s 用于 PCRE_DOTALL

    If this modifier is set, a dot metacharacter in the pattern matches all characters, including newlines. Without it, newlines are excluded. This modifier is equivalent to Perl's /s modifier. A negative class such as [^a] always matches a newline character, independent of the setting of this modifier.

这是一对夫妇比赛的样子

enter image description here


注意如果在一行的末尾找不到 ?>,它就不起作用。

所以它适用于

  • ?>');
  • ?> */

但它不适用于

<?php
  echo "actual code";
  /*
   * comment ?>
   */
?>

简而言之,如果您的代码如此困惑,您需要更好的解决方案。如果您的代码干净,它应该可以正常工作。

关于php - 使用正则表达式提取 PHP 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18431312/

相关文章:

regex - 如何为由URL stub 中动态生成的数字组成的URL设置分析目标?

php - 神秘的 JavaScript 变量变化

php - 在 html/php 中有三个单独的测验提交 session

php - 重用 MySQL 结果

php - in_array 忽略小数点后的 000

regex - 如何在 perl 正则表达式中跨换行符匹配?

regex - 如何定义对特定字符串使用 `replace-string` 的 Emacs 命令

php - Zend MultiCheckbox 输入属性

python - 将 SQL 插入语句拆分为键值对

regex - 在正则表达式中排除某个双字符