【问题标题】:Search function returns strpos() warning搜索函数返回 strpos() 警告
【发布时间】: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

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    在调用 strpos 时,strtolower($phrase) 必须以某种方式计算为空字符串,所以让我们使用一个函数来过滤掉空(子)字符串并进行更多测试。

    $phrases = preg_split('!\s+!', $phrase, -1,  PREG_SPLIT_NO_EMPTY);
    if ( empty($phrases) ) {
        trigger_error('empty phrase', E_USER_ERROR);
    }
    
    foreach ($phrases as $phrase) {
        $phrase = strtolower($phrase);
        if ( 0==strlen($phrase) ) {
            trigger_error('empty phrase', E_USER_ERROR);
        }
        $pos = strpos(strtolower($text), strtolower($phrase)); 
        if ($pos > -1) break;
    }
    // you probably should test ($pos > -1) here again
    

    另请参阅:
    http://docs.php.net/preg_split
    http://docs.php.net/trigger_error

    【讨论】:

    • 这个返回Fatal error: empty phrase,我想是因为trigger_error('empty phrase', E_USER_ERROR);吧?
    猜你喜欢
    • 2016-02-06
    • 2016-12-09
    • 2020-01-09
    • 1970-01-01
    • 2016-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-03
    相关资源
    最近更新 更多