PHP计算一个特定单词在h3标记中显示的次数


PHP Count how many times a specific word shows up in h3 tag

我需要能够计算特定单词在特定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次,但我只想数一下单词"lorim"在h3标签中出现了多少次。

我更愿意在这个项目上继续使用PHP。

非常感谢您的帮助

我会像这样使用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

您也可以使用正则表达式来执行此操作:

<?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;
     }
?>