我建议完全省略else
:
这是我的代码:
function getaname($name)
{
$result = file_get_contents('https://www.something.com');
$regex = '/<div class="classname">([^<]*)<\/div>/';
if (preg_match($regex, $result, $matches)) {
return $matches[1];
} else{
return 'N/A';}
}
[当preg_match
在div
中发现某物但我希望将其返回echo
或当它在潜水中未发现任何东西时返回N/A
时,此代码运行正常)>
<div></div>
这是我的代码:function getaname($ name){$ result = file_get_contents('https://www.something.com'); $ regex ='/
我建议完全省略else
:
function getaname($name)
{
$result = file_get_contents('https://www.something.com');
$regex = '/<div class="classname">([^<]*)<\/div>/';
if (preg_match($regex, $result, $matches)) {
return $matches[1];
}
return 'N/A';
}
我想您没有完全解释条件,我想您检查空的div
,在您的情况下为<div class="classname"></div>
。
在这种情况下,您的正则表达式仍会发现<div class="classname">
的出现,并且preg_match
返回真实值。因此,在这种情况下,您还需要检查$matches[1]
是否为空:
if (preg_match($regex, $result, $matches) && !empty($matches[1])) { return $matches[1]; } else { return 'N/A'; }
这里是小提琴https://3v4l.org/XUvUD,取消注释
$result
行,并在每种情况下查看输出。
我建议完全省略else
:
我想您没有完全解释条件,我想您检查空的div
,在您的情况下为<div class="classname"></div>
。