如何使用preg_replace_callback? [英] How to use preg_replace_callback?

查看:78
本文介绍了如何使用preg_replace_callback?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下HTML语句

[otsection]Wallpapers[/otsection]
WALLPAPERS GO HERE

[otsection]Videos[/otsection]
VIDEOS GO HERE

我想做的是将[otsection]标记替换为html div.我要抓住的是我要从1-> 2-> 3等增加div的id.

What I am trying to do is replace the [otsection] tags with an html div. The catch is I want to increment the id of the div from 1->2->3, etc..

因此,例如,上述声明应翻译为

So for example, the above statement should be translated to

<div class="otsection" id="1">Wallpapers</div>
WALLPAPERS GO HERE

<div class="otsection" id="2">Videos</div>
VIDEOS GO HERE

据我研究,最好的方法是通过preg_replace_callback在每次替换之间增加id变量.但是经过1个小时的研究,我无法使它正常工作.

As far as I can research, the best way to do this is via a preg_replace_callback to increment the id variable between each replacement. But after 1 hour of working on this, I just cant get it working.

在此方面提供的任何帮助将不胜感激!

Any assistance with this would be much appreciated!

推荐答案

使用以下内容:

$out = preg_replace_callback(
    "(\[otsection\](.*?)\[/otsection\])is",
    function($m) {
        static $id = 0;
        $id++;
        return "<div class=\"otsection\" id=\"ots".$id."\">".$m[1]."</div>";
    },
    $in);

尤其要注意,我使用了static变量.该变量会在函数调用期间持续存在,这意味着每次调用函数时变量都会递增,每次匹配都会发生.

In particular, note that I used a static variable. This variable persists across calls to the function, meaning that it will be incremented every time the function is called, which happens for each match.

此外,请注意,我在ID前面加了ots.元素ID不应以数字开头.

Also, note that I prepended ots to the ID. Element IDs should not start with numbers.

对于5.3之前的PHP:

For PHP before 5.3:

$out = preg_replace_callback(
    "(\[otsection\](.*?)\[/otsection\])is",
    create_function('$m','
        static $id = 0;
        $id++;
        return "<div class=\"otsection\" id=\"ots".$id."\">".$m[1]."</div>";
    '),
    $in);

这篇关于如何使用preg_replace_callback?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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