piccola modifica con tanto di controlli:
Codice PHP:
$str = "keyword web design che ci serve e quindi la dobbiamo evidenziare con bold e ricevere una cosa simile (vedi sotto)";
$keyword = "WEB design" ;
function snippet ( $str , $keyword , $words = 5 )
{
$left_str = '' ; $right_str = '' ; $output_string = '' ; $ts = array ( ) ; $ikey = array ( ) ;
if ( preg_match ( '/(' . $keyword . ')/i' , $str , $ikeys ) )
{
$ts = explode ( $ikeys[1] , $str ) ;
}
else
{
return 'Keyword non trovata' ;
}
if ( count ( $ts ) )
{
$left_words = array_reverse ( explode ( ' ' , $ts[0] ) ) ;
$right_words = explode ( ' ' , $ts[1] ) ;
for ( $i = 0 ; $i <= $words ; $i++ )
{
$left_str .= isset ( $left_words[$words-$i] ) ? $left_words[$words-$i] . ' ' : '' ;
$right_str .= isset ( $right_words[$i] ) ? $right_words[$i] . ' ' : '' ;
}
$output_string = $left_str . '[b]' . $ikeys[1] . '[/b] ' . $right_str ;
$output_string = ( strlen ( $left_str ) < strlen ( implode ( ' ' , $left_words ) . ' ' ) ) ? '... ' . $output_string : $output_string ;
$output_string = ( strlen ( $right_str ) < strlen ( implode ( ' ' , $right_words ) . ' ' ) ) ? $output_string . ' ...' : $output_string ;
return $output_string;
}
else
{
return 'Keyword non trovata' ;
}
}
echo 'stringa_completa: ' . $str . '
' ;
echo 'stringa_trattata:' . snippet ( $str, $keyword, 8 ) ;