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";
}
当我搜索字符串"Tennis" PHP返回"string not found"。如果我搜索的字符串属于foreach的最后一次迭代,长度为149(忽略$pre_edit变量的前五行),则只返回"找到的字符串"。你能给我一些建议如何解决这个问题吗?谢谢你!
您没有在foreach()
循环内进行搜索,因此您只会EVER获得循环检索的最后一个节点。
如果正确缩进代码,就会发现问题。应该是:
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
}
还请注意,我已将$pos == true
更改为$pos !== false
。如果您正在搜索的字符串位于字符串的开头,strpos可以并且将返回0
。但是在PHP中,0 == false
是TRUE,而0 === false
是FALSE。您需要使用严格的相等性测试(比较类型和值)来检查strpos在搜索失败时返回的布尔值FALSE。