Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
419 views
in Technique[技术] by (71.8m points)

php - How to use preg_replace_callback?

I have the following HTML statement

[otsection]Wallpapers[/otsection]
WALLPAPERS GO HERE

[otsection]Videos[/otsection]
VIDEOS GO HERE

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

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use the following:

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

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.

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


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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...