【问题标题】:Don't include bbCode in reading time and word/character counters不要在阅读时间和单词/字符计数器中包含 bbCode
【发布时间】:2016-10-10 10:29:00
【问题描述】:

我在 PHP 中使用不同的函数来帮助我计算单词、字符以及阅读时间。但他们都有一个轻微的“错误”:函数计算一切 - 包括 bbCode(带有笑脸)。我不想要那个!

function calculate_readingtime($string) {
    $word = str_word_count(strip_tags($string));
    $m = floor($word / 200);
    $s = floor($word % 200 / (200 / 60));

    $minutes = ($m != 0 ? $m.' min.' : '');
    $seconds = (($m != 0 AND $s != 0) ? ' ' : '') . $s.' sec.';

    return $minutes . $seconds;
}

$content = 'This is some text with [b]bbCode[/b]! Oh, so pretty :D And here\'s is a link too: [url="https://example.com/"]das linkish[/url]. What about an image? That\'s pretty to, you know. [img src="https://example.com/image.jpg" size="128" height="128" width="128"] And another one: [img src="https://example.com/image.jpg" height="128"]';
$reading_time = calculate_readingtime($content);
$count_words = str_word_count($content, 1, 'àáãâçêéíîóõôúÀÁÃÂÇÊÉÍÎÓÕÔÚÅåÄäÖö');
$count_chars_with_spaces = mb_strlen($content);

echo 'Reading time: '.$reading_time.'<br>';
echo 'Words: '.count($count_words).'<br>';
echo 'Characters with spaces: '.$count_chars_with_spaces;

# OUTPUT
Reading time: 16 sec.
Words: 55
Characters with spaces: 326

我希望计数器(包括阅读时间)更准确,不包括 bbCode,但包括 bbCode 内的文本(例如:包括来自 [b]bbCode[/b] 的文本 bbCode)。

我怎样才能做到这一点?

【问题讨论】:

    标签: php count bbcode


    【解决方案1】:

    实际上,使用preg_replace 从字符串中解析出BBCode 相对容易,尤其是在PHP 等支持PCRE 库的语言中。假设您的 BBCode 语法有一些问题,这是最短的方法:

    preg_replace('@\[(?:\w+(?:="(?>.*?"))?(?: \w+="(?>.*?"))*|/\w+)]@s', '', $content);
    

    Demo on Regex101

    或者用结束标签和嵌套更精确的更好方法:

    function parse($str) {
        return preg_replace_callback('@\[(\w+)(?:="(?>.*?"))?(?: \w+="(?>.*?"))*](?:(.*?)\[/\1])?@s',
            function($matches) { return $matches[2] ? parse($matches[2]) : ''; },
            $str
        );
    }
    

    Demo on Ideone

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-08
      • 1970-01-01
      • 2014-07-17
      • 1970-01-01
      • 2014-05-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多