我有以下 HTML 语句
[otsection]Wallpapers[/otsection]
WALLPAPERS GO HERE
[otsection]Videos[/otsection]
VIDEOS GO HERE
我想做的是将 [otsection] 标签替换为 html div。问题是我想从 1->2->3 等增加 div 的 id。
例如,上面的语句应该翻译为
<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 个小时的努力,我就是无法让它工作。
任何对此的帮助将不胜感激!
使用以下内容:
$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
多变的。该变量在对函数的调用中持续存在,这意味着每次调用该函数时该变量都会递增,每次匹配都会发生这种情况。
另外,请注意我在前面添加了ots
到身份证。元素 ID 不应以数字开头。
对于 5.3 之前的 PHP:
$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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)