【发布时间】:2014-10-17 21:20:54
【问题描述】:
我正在使用this solution 在 wordpress 中搜索短语。功能是这样的
function excerpt($text, $phrase, $radius = 100, $ending = "...") {
$phraseLen = strlen($phrase);
if ($radius < $phraseLen) {
$radius = $phraseLen;
}
$phrases = explode (' ',$phrase);
foreach ($phrases as $phrase) {
$pos = strpos(strtolower($text), strtolower($phrase));
if ($pos > -1) break;
}
$startPos = 0;
if ($pos > $radius) {
$startPos = $pos - $radius;
}
$textLen = strlen($text);
$endPos = $pos + $phraseLen + $radius;
if ($endPos >= $textLen) {
$endPos = $textLen;
}
$excerpt = substr($text, $startPos, $endPos - $startPos);
if ($startPos != 0) {
$excerpt = substr_replace($excerpt, $ending, 0, $phraseLen);
}
if ($endPos != $textLen) {
$excerpt = substr_replace($excerpt, $ending, -$phraseLen);
}
return $excerpt;
}
问题是,自从 wordpress 4.0 停止工作,我收到Warning: strpos(): Empty needle 警告。
我尝试检查 $pos 是否为空、null 等。还有 $text 和 $phrase,但没有运气。
谁有解决这个问题的办法?
编辑:VolkerK 的答案是好的,但我想搜索不返回错误,所以我选择了:
if(empty($phrase)){
return;
}
在函数的开头。工作正常。 :D
【问题讨论】: