我对你们有疑问。让我说我正在写一篇文章,我有10个关键字,它们应该在文中提到。如果提到关键字,我需要计算这个单词在文本中的次数。并且所有数量应显示在textarea的顶部或底部,例如在跨度或输入中,这无关紧要。但是如何?
更新:
抱歉,我忘了提到我想在我输入textarea时这样做,它需要在jquery中制作。function ck_jq()
{
var charsCount = CKEDITOR.instances['article'].getData().replace(/<("[^"]*"|'[^']*'|[^'">])*>/gi, '').replace(/^\s+|\s+$/g, '');
var wordCount = CKEDITOR.instances['article'].getData().replace(/[^\w ]/g, "").split(/\s+/);
var max = <?php echo $orderInfo->wordstarget; ?>;
//var max = 5;
if (wordCount >= max) {
var over = max - wordCount.length;
$("#wordstarget").css('color', 'red');
$("#characterscount").css('color', 'red');
$("#words").css('color', 'red');
$("#wordsleft").css('color', 'red');
// $("#wordscount").text(len.length + " characters and \n" + wordCount + " words in this text. Words target: " + max +". Words left: "+ char);
$("#wordstarget").text(max + " words target");
$("#characterscount").text(charsCount.length + " characters");
$("#words").text(wordCount.length + " words");
$("#wordsleft").text(over +" words left");
//$("#wordscount").css('color', 'red');
//$("#wordscount").text(len.length + " characters and \n" + wordCount + " words in this text. Words target: " + max +". Words left: "+ over);
} else {
var char = max - wordCount.length;
$("#wordstarget").css('color', 'green');
$("#characterscount").css('color', 'green');
$("#words").css('color', 'green');
$("#wordsleft").css('color', 'green');
// $("#wordscount").text(len.length + " characters and \n" + wordCount + " words in this text. Words target: " + max +". Words left: "+ char);
$("#wordstarget").text(max + " words target");
$("#characterscount").text(charsCount.length + " characters");
$("#words").text(wordCount.length + " words");
$("#wordsleft").text(char +" words left");
}
}
我用它来计算单词和字符。使用此CKEDITOR.instances['article'].getData()
我可以获取所有ckeditor文本,然后搜索确切的单词。
答案 0 :(得分:6)
匹配部分单词(foo匹配foobar)
PHP:
echo substr_count("a foo bar of foos and such","foo");//2
JS:
"a foo bar of foos and such".match(/foo/g).length;//2
仅匹配完整字词,不匹配
PHP:
echo preg_match('#\bfoo\b#',"a foo bar of foos and such");//1
JS:
"a foo bar of foos and such".match(/\bfoo\b/g).length;//1
更新:JS功能
function word_count(str,word,strict)
{
strict = typeof strict == "boolean" ? strict : true;
var b = strict ? '\\b' : '';
var rex = new RegExp(b+word+b,"g");
return str.match(rex).length;
}
//where element.innerHTML = "a foo bar of foos and such"
word_count(element.innerHTML,'foo');//1
word_count(element.innerHTML,'foo',false);//2
第三个参数strict
默认为true,设置为false时不需要字边界,允许foo
匹配foobar
答案 1 :(得分:3)
答案 2 :(得分:1)
实际上有一个内置函数来计算名为str_word_count()的字符串中单词的出现次数,它返回一个可以使用array_count_values计算的单词数组,它给出了一个由单词索引的计数数组然后,您可以array_intersect_key()添加关键字列表。
修改强>
$string = "It behooves us to offer the prospectus for our inclusive syllabus";
$keywords = array('syllabus', 'prospectus', 'inclusive');
$counts = array_intersect_key(
array_count_values(
str_word_count($string, 1)
),
array_flip($keywords)
);
var_dump($counts);