现在,下面的代码对html文档执行测试,看看是否有h1或h2标签包含字符串$ title。代码完美无瑕。
$s1='random text';
$a1='random anchor text';
$href1='http://www.someurl.com';
$document = new DOMDocument();
$libxml_previous_state = libxml_use_internal_errors(true);
$document->loadHTML($str);
libxml_use_internal_errors($libxml_previous_state);
$tags = array ('h1', 'h2');
$texts = array();
foreach($tags as $tag)
{
$elementList = $document->getElementsByTagName($tag);
foreach($elementList as $element)
{
$texts[$element->tagName] = strtolower($element->textContent);
}
}
if(in_array(strtolower($title),$texts)) {
echo '<div class="success"><i class="fa fa-check-square-o" style="color:green"></i> This article used the correct title tag.</div>';
} else {
echo '<div class="error"><i class="fa fa-times-circle-o" style="color:red"></i> This article did not use the correct title tag.</div>';
}
我需要运行三个测试,首先我需要扫描的$ s1的存在的文件,但不知道这一点。通过工作代码,它正在寻找h1或h2标签内的完全匹配。然而,对于$ s1我不寻找完全匹配,只是在任何文本存在的地方 - 无论是否包含其他文本。
然后,我需要另一个精确匹配测试来查找“a”文本中的$ a1,并且还需要测试href是否存在$ href1。
我不知道如何做这些测试。我相信我可以将$ a1测试看作是另一个精确匹配,但不知道如何执行href测试,也不能扫描可能被其他文本包围的字符串。
希望这一切都有道理。
更新
我需要一个解决方案,让我回显一个单一“是字符串是否存在”或“不,它不需要”。类似于当前测试回声的唯一方式,而不是每个回路。我需要每次测试都做一次。
示例结果会是什么样子:
yes $s1 is in the document
no $s1 is not in the document
yes $href1 is an href in the document
no $href1 is not an href in the document
yes $a1 is an anchor text in the document
no $a1 is not an anchor text in the document
我也相信我应该使用SUBSTR(),但我不知道究竟如何。
希望得到一些工作实例和详细解释。
一些提示:1,你可以用'的foreach($文档 - >的getElementsByTagName( '*')为$元素) {'选择所有元素,然后检查'$ element-> textContent'作为你的字符串。 2-请查看[此链接](http://www.the-art-of-web.com/php/html-xpath-query/)**第2步**,以了解如何寻找你的''标记... – EhsanT
不会在第一个提示中,它只会返回,如果它完全匹配。我的意思是,如果一个元素的内容是“随机字符串和单词,然后$ s1和更多的字符和单词” – Bruce
所以在这种情况下,你可以使用正则表达式来匹配你的字符串 – EhsanT