Sunday, 15 May 2011

php - Search function returns strpos() warning -



php - Search function returns strpos() warning -

i'm using this solution searching phrases in wordpress. function this

function excerpt($text, $phrase, $radius = 100, $ending = "...") { $phraselen = strlen($phrase); if ($radius < $phraselen) { $radius = $phraselen; } $phrases = explode (' ',$phrase); foreach ($phrases $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); } homecoming $excerpt;

}

the thing is, since wordpress 4.0 stopped working, , i'm getting warning: strpos(): empty needle warning.

i've tried checking $pos if it's empty, null, etc. $text , $phrase, no luck.

anyone has solution problem?

edit: reply volkerk ok, i'd search not homecoming error went with:

if(empty($phrase)){ return; }

in origin of function. works fine. :d

somehow strtolower($phrase) must evaluate empty string when calling strpos, let's utilize function filters out empty (sub-)strings , set in more test.

$phrases = preg_split('!\s+!', $phrase, -1, preg_split_no_empty); if ( empty($phrases) ) { trigger_error('empty phrase', e_user_error); } foreach ($phrases $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; } // should test ($pos > -1) here 1 time again

see also: http://docs.php.net/preg_split http://docs.php.net/trigger_error

php wordpress

No comments:

Post a Comment