2016-10-10 27 views
1

PHP에서 단어, 문자 및 읽기 시간을 계산하는 데 도움이되는 다른 기능을 사용합니다. 하지만 그들은 모두 하나의 "오류"를 가지고 있습니다 :이 기능은 bbCode (스마일리 포함)를 포함한 모든 것을 계산합니다. 나는 그것을 원하지 않는다!읽기 시간과 단어/문자 카운터에 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 포함).

어떻게하면됩니까?

답변

0

특히 PCRE 라이브러리를 지원하는 PHP와 같은 언어에서 preg_replace을 사용하여 BBCode를 문자열에서 파싱하는 것은 상대적으로 쉽습니다.

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

Demo on Regex101

또는 종료 태그와 중첩 더 정밀한의 더 나은 방법 :

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

Demo on Ideone

당신의 BBCode는 구문에 대해 몇 가지를 가정하면, 여기에 짧은 방법