1

我需要能够计算特定单词在特定 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。

非常感谢您的帮助

4

2 回答 2

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
于 2012-09-01T17:26:32.417 回答
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;
     }

?>
于 2012-09-01T17:33:59.080 回答