[RESOLU] htmlspecialchars et UTF-8 dans ma fonction

Eléphanteau du PHP | 25 Messages

14 mars 2017, 03:10

Bonjour,
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
english 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
ou
d’un-e ivrogne solitaire.
Ma fonction
$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 aide
Yule

Eléphant du PHP | 63 Messages

14 mars 2017, 15:08

Bonjour. Il manque le u pour UTF-8 sans quoi un caractère sur plusieurs octets pourrait être scinder dans ses marqueurs UTF-8.
preg_match_all("#(\W.{0,$span}\W)($words)(\W.{0,$span}\W)#iu", /* ajouter le u après ou avant le i */
Dans l'autre fonction il y a aussi le s pour permettre au méta-caractère point d'inclure \n et donc ne pas être bloqué par un retour à la ligne.

Eléphanteau du PHP | 25 Messages

14 mars 2017, 22:32

Parfait merci bien !