首页 文章

计算wordpress博客文章中的段落总数

提问于
浏览
0

我写了一个小片段来计算任何WordPress博客文章中段落的总数,以便它可以返回该数字,并根据该数字我可以做其他的事情 . 但它似乎没有正常工作 . 有谁看看,告诉我为什么?

What I Want my code to return?

我希望我的代码返回每篇博文上的段落总数 .

这是我的代码:

//Check paragraph count on a blog post
function __check_paragraph_count_blog() {
    if ( is_singular( 'post' ) ) {
        $content = apply_filters('the_content', $post->post_content);
        $contents = explode("</p>", $content);
        $p_count = 1;
        foreach($contents as $content) {
            $p_count++;
        }

        return $p_count;
    }
}

任何帮助将受到高度赞赏 .

1 回答

  • 2

    请改用PHP的正则表达式匹配器 .

    像这样的东西应该做的伎俩:

    $subject = "<p>paragraph one</p>
        <p>paragraph two</p>
        <p>paragraph three</p>
        <p>paragraph four</p>";
    $pattern = "/<p>.*?<\/p>/gm"; // Global & Multiline
    $paragraph_count = preg_match_all($pattern,$subject);
    

    模式的一个例子:https://regex101.com/r/oE8fI7/1

    更多信息:http://php.net/manual/en/function.preg-match-all.php

相关问题