如何包装DIV各地 标签?(How to wrap div around

tag?)

2019-11-03 21:57发布

我使用WordPress作为CMS系统,我想每包p在某些HTML我需要在我的网站风格和定位标签。

我已经找到了一段代码,奇妙做到这一点对我来说,但现在的问题是矫枉过正。

这里是:

function tekst_wrapper($content) {
    // match any p tags
    $pattern = '~<p.*</p>~';
    preg_match_all($pattern, $content, $matches);

    foreach ($matches[0] as $match) {
        // wrap matched p tag with div
        $wrappedframe = '<div>' . $match . '</div>';

        //replace original p tag with new in content
       $content = preg_replace($pattern, $wrappedframe, $content);
    }

    return $content;    
}
add_filter('the_content', 'tekst_wrapper');

这增加了围绕每个p标签的div标签。 但对于每一个p标签有在后,它开始在每个p标签增加更多的div标签。 所以说,我有四个p标签,生成的HTML将是:

 <div> <div> <div> <div> <p>random text</p> </div> </div> </div> </div> <div> <div> <div> <div> <p>random text</p> </div> </div> </div> </div> <div> <div> <div> <div> <p>random text</p> </div> </div> </div> </div> <div> <div> <div> <div> <p>random text</p> </div> </div> </div> </div> 

显然,这不是我所需要的,因为我只是希望每个p标签被包裹在一个div标签(或什么我替换HTML将是)。 现在我的PHP技能是不是很大,但我相信在foreach导致其添加div标签,每发现在比赛$matches阵列? 有没有什么办法解决这一问题?

Answer 1:

你在你的HTML一样<p>标签的多个副本,并要更换他们每个人对你的foreach循环每次迭代。 使用preg_replace函数或preg_replace_callback代替foreaching。

function tekst_wrapper($content) {
    // match any p tags
    $pattern = '~<p.*?</p>~';
    return preg_replace_callback($pattern, function($matches) {
        return '<div>' . $matches[0] . '</div>';
    }, $content);
}
add_filter('the_content', 'tekst_wrapper');

请注意,在模式的问号,使之懒惰。



Answer 2:

这将被预期的,因为preg_match_all是匹配的p标签的所有4个,然后在foreach,preg_replace函数被替换标记的所有4每次循环贯穿,在总的循环运行4次和所有标签被取代所得的4倍在上面的输出。

要解决此简单地使用的preg_replace和放弃preg_match_all,为的preg_replace将取代它所有的,所以这是你到底是什么了:

function tekst_wrapper($content) {
  return preg_replace_callback('~<p.*</p>~i', function($match) {
    return '<div>' . $match[0] . '</div>';
  }, $content);
}

add_filter('the_content', 'tekst_wrapper');

IVE更新正则表达式包括“i”的在它的端部,这使得它不区分大小写。 这是因为HTML不区分大小写。

希望这可以帮助。



文章来源: How to wrap div around

tag?

标签: php wordpress