【问题标题】:PHP Check if word exists between h2 tagsPHP检查h2标签之间是否存在单词
【发布时间】:2015-03-27 08:29:05
【问题描述】:

我有这个 SEO 脚本,我在 $row['content'] 中查找 $row_meta['keyword'] 这是我的搜索焦点关键字.

我想检查是否有 h1、h2、h3 或 h4 标签包含我的关键字。例如,如果我的 $row_meta['keyword'] = "test"; 这个文本应该是匹配的:

This is my text
<h2>We just want to test</h2>
but this text containing test is not a match, only between h tags.

有人能帮帮我吗?

我有类似的东西,它正在测试我是否有任何包含带有我的关键字的 alt 标签的 img 标签,这是我的代码:

$dom = new DOMDocument();
$dom->loadHTML($row['content']);
foreach ($dom->getElementsByTagName('img') as $img) {
    $alt = $img->getAttribute('alt');
    if (preg_match("/\b".$row_meta['keyword']."\b/", $alt)) {
        $counter++;
    }
}

【问题讨论】:

    标签: php pattern-matching preg-match match h2


    【解决方案1】:

    不确定这是否正确(我已经很久没有做过 php 并且不确定这是否是正确的解析器)但我认为您可以执行以下操作

    $dom = new DOMDocument();
    $dom->loadHTML($row['content']);
    foreach ($dom->getElementsByTagName('h2') as $h2) {
        $text = $h2->nodeValue;
        if (preg_match("/\b".$row_meta['keyword']."\b/", $text)) {
            $counter++;
        }
    }
    

    【讨论】:

    • 很遗憾,没有匹配项 :-(
    • plaintext 是否返回任何内容 - 它可能是错误的解析器
    • print_r($text);什么都不返回
    • 尝试使用nodeValue。文档对解析器来说不是很好
    • 如果您不确定$row_meta['keyword'] 的潜在内容,那么您可能希望转义其中的任何字符,否则会破坏正则表达式,例如/ * + [ 等使用嵌套的preg_replace。
    猜你喜欢
    • 2015-05-19
    • 2013-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-17
    • 2017-12-11
    • 1970-01-01
    相关资源
    最近更新 更多