且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何用正则表达式模式替换文本并在替换文本中集成一个计数器?

更新时间:2023-02-23 14:36:18

最终在TiMESPLiNTER的帮助下解决了这个问题(感谢他!),不知道未带上 $ 1 并且您必须在回调函数中调用变量 $ matches 并获得 $ matches [1] 而不是$ 1.

Eventually solved it with the help of TiMESPLiNTER (give him the credit!), didn't know $1 didn't get brought along and that you have to call a variable $matches in the callback function and get $matches[1] instead of $1.

$counter = 1;

function parse(){
    function cb($matches){
        global $counter;

        return '<span class="b">'. $this->counter .'. ' . $matches[1] . '</span>';
    }

    $string = preg_replace_callback("_\[b\](.*?)\[/b\]_si", 'cb', $string);
}