我使用的是简单的html dom解析器
foreach($html->find('a') as $element) {
//produce results
if(strpos($element, 'string')) {
$myarray[] = $element->href;
}
}
与
foreach($html->find('a') as $element) {
//not producing result
if(strpos($element->href, 'string')) {
$myarray[] = $element->href;
}
}
为什么当我在元素->href中添加strpos函数时,即使href有字符串关键字,它也永远不会检测到字符串。
strpos('monkey', 'm')
将返回0
。0
将被PHP视为false。如果$element->href
从string
开始,它将不会进入If.
使用
strpos(..., ...) === false
或
strpos(..., ...) !== false
除了Sjoerd提到的(进行严格的相等测试)之外,问题可能是将对象传递到strpos,而不是字符串。这应该有效:
foreach($html->find('a') as $element) {
//not producing result
if(strpos( (string) $element->href, 'string') !== false) {
$myarray[] = $element->href;
}
}