如何用正则表达式模式替换文本并在替换文本中集成一个计数器? [英] How to replace text with a regex pattern and integrate a counter in the replacement text?

查看:62
本文介绍了如何用正则表达式模式替换文本并在替换文本中集成一个计数器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

function parse($string){
    $counter = 0;
    
    $string = preg_replace("_\[b\](.*?)\[/b\]_si", '<span class="b">'. $counter .'. $1</span>', $string, -1, $counter);
    
    return $string;
}

我正在尝试制作一个ubb解析器,用于解析标签并将计数放在其前面:

I'm trying to make a ubb parser, that parses tags and put the counting in front of it:

[b]Hey[/b]
[b]Hello[/b]

应返回此:

<span class="b">1. Hey</span>
<span class="b">2. Hello</span>

但是返回此:

<span class="b">1. Hey</span>
<span class="b">1. Hello</span>

所以在上面的函数旁边,我已经尝试过了:

So beside the function above, I've tried this:

function parse($string){
    
    $counter = 0;
    
    $string = preg_replace_callback(("_\[b\](.*?)\[/b\]_si", function(){
        '<span class="b">'. $counter++ .'. $1</span>',
    }, $string);
}

但是那和顶部的功能不起作用.我在做什么错和/或可以尝试?

but that, and the function at the top, didn't work. What am I doing wrong and/or could I try?

推荐答案

最终在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);
}

这篇关于如何用正则表达式模式替换文本并在替换文本中集成一个计数器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆