PHP - 使用正则表达式更改文本
PHP - Change of text with regex
我知道这个问题已经被问过很多次了,但是我在网站上搜索过,没有找到解决方案。
我正在尝试 "override" php 的函数 echo
,我的目标是过滤所有文件中的所有 php 输出。
我需要用以下指令替换 html 文本:
echo"SOME STRING"
与:
echo_custom("SOME STRING")
和
echo("SOME STRING")
和
echo_custom("SOME STRING)
这是完成这项工作的一种方法:
$in = <<<EOD
echo"SOME STRING"
echo("SOME STRING")
echo"SOME STRING";
echo("SOME STRING");
EOD;
$out = preg_replace('/echo\(?(.+?)\)?(?=;|\R)/', 'echo_custom()', $in);
echo $out,"\n";
输出:
echo_custom("SOME STRING")
echo_custom("SOME STRING")
echo_custom("SOME STRING");
echo_custom("SOME STRING");
解释:
echo : literally
\(? : optional opening parenhesis
( : start group 1
.+? : 1 or more any character but newline, not greedy
) : end group 1
\)? : optional closing parenthesis
(?= : positive lookahead, make sure we have after
; : semicolon
| : OR
\R : any kind of linebreak
) : end lookahead
我知道这个问题已经被问过很多次了,但是我在网站上搜索过,没有找到解决方案。
我正在尝试 "override" php 的函数 echo
,我的目标是过滤所有文件中的所有 php 输出。
我需要用以下指令替换 html 文本:
echo"SOME STRING"
与:
echo_custom("SOME STRING")
和
echo("SOME STRING")
和
echo_custom("SOME STRING)
这是完成这项工作的一种方法:
$in = <<<EOD
echo"SOME STRING"
echo("SOME STRING")
echo"SOME STRING";
echo("SOME STRING");
EOD;
$out = preg_replace('/echo\(?(.+?)\)?(?=;|\R)/', 'echo_custom()', $in);
echo $out,"\n";
输出:
echo_custom("SOME STRING")
echo_custom("SOME STRING")
echo_custom("SOME STRING");
echo_custom("SOME STRING");
解释:
echo : literally
\(? : optional opening parenhesis
( : start group 1
.+? : 1 or more any character but newline, not greedy
) : end group 1
\)? : optional closing parenthesis
(?= : positive lookahead, make sure we have after
; : semicolon
| : OR
\R : any kind of linebreak
) : end lookahead