gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 19:10:59 24 4
gpt4 key购买 nike

我想用正则表达式提取本节的整个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com