gpt4 book ai didi

php - preg_replace,值显示为 $1.. 但使用了修改器 "e"

转载 作者:行者123 更新时间:2023-12-04 05:18:50 26 4
gpt4 key购买 nike

我试图用 preg_replace 制作一个 bbCode 系统,它运行一个函数,但由于某种原因,输出仅为 1 美元,即使我添加了 'e' 修饰符。

任何想法如何解决这个问题?

源代码:

            function bbcode($value){
$pattern[0] = "/\{register\}(.*?)\{\/register\}/sie";
$replace[0] = register('$1'); //"<pre>$1</pre>";
$bbcoded = preg_replace($pattern, $replace, $value);
return $bbcoded;
}

function register($var) {
echo $var;
}

$content = '
{b}text{/b}
{register}
"register" = "setting",
"name" = "title",
"order" = "1"
{/register}
some text
{register}
"register" = "setting",
"name" = "url",
"order" = "3"
{/register}
some more {b}t{/b}e{b}xt{/b}
{register}
"register" = "setting",
"name" = "description",
"order" = "2"
{/register}
text text
';

$content = bbcode($content);

看看它在行动: http://sandbox.onlinephpfunctions.com/code/08459c4fec1919e6089d3849e154ba7a83900fd7

最佳答案

您应该使用 preg_replace_callback() 相反:

 $pattern = "/\{register\}(.*?)\{\/register\}/si"; // NO /e modifier!
$bbcoded = preg_replace_callback($pattern, 'register', $value);

function register($var)
{
// $var[0] is the whole match
// $var[1] is the part between {register} and {/register}

// whatever you return here will be the replacement string
return $var[0];
}
preg_replace_callback()的第二个参数是 callable在找到的每个匹配项上运行,其返回值用作替换。

更新
/e 的语法替换将是这个顺便说一句(整个事情应该是一个字符串):
$bbcoded = preg_replace_callback($pattern, "register('$1')", $value);

关于php - preg_replace,值显示为 $1.. 但使用了修改器 "e",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13917893/

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