Dans ma fonction ci-dessous que j'utilise avec mon moteur de recherche, j'essaye d'intégrer dans le foreach, un htmlspecialchars et UTF-8 sans y parvenir...
La fonction tourne mais ne corrige pas mon texte qui s'affiche ainsi
ouenglish météo météo bizerte, 23 météo chebba, 53 météo gabes, 81 météo houmet essouk, 82 météo la marsa, 11 mét�...�o
Ma fonctiondun-e ivrogne solitaire.
$keywordsy = "$keywords";
function get_snippet($keywordsy, $texte) {
$snippet='';
$span = 100;
$strlen_max = 350;
$words = join('|', explode(' ', preg_quote($keywordsy)));
preg_match_all("#(\W.{0,$span}\W)($words)(\W.{0,$span}\W)#i", " $texte ", $matches);
foreach($matches[0] as $match) {
if (!$match = trim($match)) continue;
if (isset($snippet)) $snippet .= "$match..."; else $snippet = "...$match...";
if (strlen($snippet.htmlspecialchars($match[0], 'UTF-8')."... ") > $strlen_max) break;
}
$snippet = preg_replace("#($words)#i", '<b>$1</b>', $snippet);
return $snippet;
}
Auparavant, j'utilisais une autre fonction qui ne satisfaisait plus à mes besoins mais qui avait l'avantage de corriger les erreurs sur le texte...l'ancienne fonction
$keywordsy = "$keywords";
function snippet_max($texte, $keywordsy, $strlen_max) {
$keywordsy = trim(preg_replace("#( [[:alnum:]]{1,2} )#Ui", " ", " ".$keywordsy." ")); // ajout d'un espace avant et après
$words = join('|', explode(' ', preg_quote($keywordsy)));
//lookahead/behind assertions ensures cut between words
$s = '\s\x00-/:-@\[-`{-~'; //character set for start/end of words
preg_match_all('#(?<=['.$s.']).{1,100}(('.$words.').{1,100})+(?=['.$s.'])#uis', $texte, $matches, PREG_SET_ORDER);
$result = "";
foreach($matches as $line) {
if (strlen($result.htmlspecialchars($line[0], 0, 'UTF-8')."... ") > $strlen_max) break;
$result .= htmlspecialchars($line[0], 0, 'UTF-8')."... ";
}
//highlight
$result = preg_replace('#'.$words.'#iu', "<span class=\"highlight_word\">\$0</span>", $result);
return $result;
}
D'avance merci pour votre aideYule