使用 PHP preg 函数查找 html 标签之间特定非字母数字字符的计数

Find the count of particular non alpha numeric character between the html tags by using PHP preg functions

我有一部分 HTML 字符串,如下所示,是我从网页抓取中获得的。

$scraping_html = "<html><body>
....
<div id='ctl00_ContentPlaceHolder1_lblHdr'>some text here with &. some text here.</div>
....</body></html>";

我想通过使用 PHP 计算特定 div 之间的 &。是否可以使用任何 PHP preg 函数?提前致谢。

困难的部分是获取文本节点(我假设这就是您遇到的问题)。根据需要的可靠性,您有两种选择(只是示例代码,未经实际测试):

  • 好老strip_tags():

    $plain_text = strip_tags($scraping_html);
    
  • 正确DOM parser:

    $dom = new DOMDocument();
    libxml_use_internal_errors(true);
    $dom->loadHTML($scraping_html);
    libxml_use_internal_errors(false);
    $xpath = new DOMXPath($dom);
    $plain_text = '';
    foreach ($xpath->query('//text()') as $textNode) {
        $plain_text .= $textNode->nodeValue;
    }
    

要计数,您有例如substr_count().

要获取给定示例中 & 的数量,请使用 DOMDocument:

$html = <<<EOD
<html><body>
<div id='ctl00_ContentPlaceHolder1_lblHdr'>some text here with &. some text here.</div>
</body></html>
EOD;

$dom = new DOMDocument;
$dom->loadHTML($html);
$ele = $dom->getElementById('ctl00_ContentPlaceHolder1_lblHdr');
echo substr_count($ele->nodeValue, '&');