2

我试图用 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

4

2 回答 2

2

您应该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()是一个可调用的,在找到的每个匹配项处运行,它的返回值用作替换。

更新

替换的语法/e是这个顺便说一句(整个事情应该是一个字符串):

$bbcoded = preg_replace_callback($pattern, "register('$1')", $value);
于 2012-12-17T16:23:15.527 回答
1

基本的php语法...

            $replace[0] = register("$1"); //"<pre>$1</pre>";
                                   ^--^--

使用'for 引号的字符串不会插入变量。同样,您的register()函数正在ECHOING您传入的值。因此,您$register[0]将成为 register 函数的返回值,该值将为 null - register 不返回任何内容。

于 2012-12-17T16:21:41.753 回答