我需要能够计算特定单词在特定html标记中显示的次数。目前,我只能计算标签中显示的单词总数。而且我可以计算文档中单词显示总数的次数,但是我无法计算出如何计算单词在h3标签中出现的次数。例如。
我需要的例子:
Sample text here, blah blah blah, lorem ipsum
<h3>Lorem is in this h3 tag, lorem.</h3>
lorem ipsum dolor....
<h3>This is another h2 with lorem in it</h3>
因此,当您看到“lorem”这个词在该代码中有4次,但我只想计算“lorem”这个词出现在h3标签中的次数。
我更喜欢在这个项目上继续使用PHP。
非常感谢您的帮助
答案 0 :(得分:2)
我会像这样使用DOMDocument:
$string = 'Sample text here, blah blah blah, lorem ipsum
<h3>Lorem is in this h3 tag, lorem.</h3>
lorem ipsum dolor....
<h3>This is another h2 with lorem in it</h3>';
$html = new DOMDocument(); // create new DOMDocument
$html->loadHTML($string); // load HTML string
$cnt = array(); // create empty array for words count
foreach($html->getElementsByTagName('h3') as $one){ // loop in each h3
$words = str_word_count(strip_tags($one->nodeValue), 1, '0..9'); // count words including numbers
foreach($words as $wo){ // create an key for every word
if(!isset($cnt[$wo])){ $cnt[$wo] = 0; } // create key if it doesn't exit add 0 as word count
$cnt[$wo]++; // increment it's value each time it's repeated - this will result in the word having count 1 on first loop
}
}
var_export($cnt); // dump words and how many it repeated
答案 1 :(得分:0)
您还可以使用正则表达式执行此操作:
<?php
$string = 'Sample text here, blah blah blah, lorem ipsum
<h3>Lorem is in this h3 tag, lorem.</h3>
lorem ipsum dolor....
<h3>This is another h2 with lorem in it</h3>';
preg_match_all("/lorem(?=(?:.(?!<h3>))*<\/h3>)/i", $string, $matches);
if (isset($matches[0])) {
$count = count($matches[0]);
} else {
$count = 0;
}
?>