首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >从帖子内容的html标记中排除标记链接

从帖子内容的html标记中排除标记链接
EN

Stack Overflow用户
提问于 2018-06-28 05:30:33
回答 1查看 83关注 0票数 1

请我想实现从下面的代码排除<h2>, <a> and <img> html标签的目标。我正在尝试用帖子内容中的链接替换标签关键字,并排除标签链接,使其不影响我上面列出的html标签。

代码语言:javascript
复制
function link_words( $text ) {
                $tags = get_tags();
                if ( $tags ) {
                    foreach ( $tags as $tag ) {
                        $from = '/' . $tag->name . '/';
                        $to = sprintf( '<a href="%s">%s</a>', esc_url( get_term_link( $tag ) ), esc_html( $tag->name ) );
                        $text = preg_replace($from, $to , $text, 2);
                    }
                }
                return $text;
            }
            add_filter( 'the_content', 'link_words' );

请大师进屋,有没有出去的路。我是wp函数编程的新手。

EN

回答 1

Stack Overflow用户

发布于 2018-06-28 08:23:44

对于简单的超文本标记语言,你可以做一个str_replace:

代码语言:javascript
复制
$text = str_replace(array("<h2>","</h2>"), "", $text);

要剥离这些更复杂的标记:

代码语言:javascript
复制
$text = preg_replace("/<img[^>]+\>/i", "", $text);
$text = preg_replace("/<a\s[^>]+\>/i", "", $text);

我刚刚测试了下面的代码,它似乎可以工作:

代码语言:javascript
复制
function link_words( $text ) {

    $text = str_replace(array("<h2>","</h2>","</a>"), "", $text);
    $text = preg_replace("/<img[^>]+\>/i", "", $text);
    $text = preg_replace("/<a\s[^>]+\>/i", "", $text);
    return $text;

}
add_filter( 'the_content', 'link_words' );
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51071707

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档