PHP简单HTML DOM搜索问题 header('Content-Type:text/html;charset=utf-8'); 包括“simple_html_dom.php”; $html=file\u get\u html('http://www.wettpoint.com/results/soccer/uefa/uefa-cup-final.html'); $cells=$html->find('table[class=gen]tr'); foreach($cells作为$cell){ $pre_edit=$cell->纯文本。“”; echo$pre_编辑; } $pos=strpos($pre_编辑,“网球”); var_dump($pos); 如果($pos==true){ echo“找到字符串!”; } 其他的 { 回显“未找到字符串”; }
当我搜索字符串“Tennis”时,PHP返回“string not found”。如果搜索属于的字符串(忽略$pre_edit var的前五行),它只返回“string found”。关于如何解决这个问题,你能给我一些建议吗?谢谢大家! 您没有在PHP简单HTML DOM搜索问题 header('Content-Type:text/html;charset=utf-8'); 包括“simple_html_dom.php”; $html=file\u get\u html('http://www.wettpoint.com/results/soccer/uefa/uefa-cup-final.html'); $cells=$html->find('table[class=gen]tr'); foreach($cells作为$cell){ $pre_edit=$cell->纯文本。“”; echo$pre_编辑; } $pos=strpos($pre_编辑,“网球”); var_dump($pos); 如果($pos==true){ echo“找到字符串!”; } 其他的 { 回显“未找到字符串”; },php,dom,Php,Dom,当我搜索字符串“Tennis”时,PHP返回“string not found”。如果搜索属于的字符串(忽略$pre_edit var的前五行),它只返回“string found”。关于如何解决这个问题,你能给我一些建议吗?谢谢大家! 您没有在foreach()循环中进行搜索,因此只能获得循环检索到的最后一个节点 如果正确地缩进代码,就会看到问题所在。应该是: header('Content-Type: text/html; charset=utf-8'); include 'simple_
foreach()
循环中进行搜索,因此只能获得循环检索到的最后一个节点
如果正确地缩进代码,就会看到问题所在。应该是:
header('Content-Type: text/html; charset=utf-8');
include 'simple_html_dom.php';
$html = file_get_html('http://www.wettpoint.com/results/soccer/uefa/uefa-cup-final.html');
$cells = $html->find('table[class=gen] tr');
foreach($cells as $cell) {
$pre_edit = $cell->plaintext . '<br/>';
echo $pre_edit;
}
$pos = strpos($pre_edit, "Tennis");
var_dump($pos);
if ($pos == true) {
echo "string found!";
}
else
{
echo "string not found";
}
还请注意,我已将
$pos==true
更改为$pos!==错误
。如果要搜索的字符串位于字符串的开头,strpos可以并且将返回0
。但是在PHP中,0==false
为真,而0==false
为假。您需要使用比较类型和值的严格相等性测试来检查搜索失败时strpos返回的布尔值FALSE。非常感谢,这很有帮助,对于所述字符串的第一次出现显示一条消息,例如“找到”或“未找到”如何对于所有的foreach迭代?那么不要在循环中进行输出。如果您只是想知道字符串是否存在于任何节点中,那么只需break()代码>找到循环时退出循环。或者,只要找到匹配项,就使用计数器执行$x++
。如果循环结束后$x为非零,则有那么多匹配项。
foreach($cells as $cell) {
$pre_edit = $cell->plaintext . '<br/>';
echo $pre_edit;
$pos = strpos($pre_edit, "Games");
var_dump($pos);
if ($pos !== false) {
echo "string found!";
} else {
echo "string not found";
}
}
foreach($cells as $cell) {
blah blah
}
if (strpos(...))) {
blah blah
}