1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| function search($wordSearch, $text, $nbWords = 10) {
//On enlève la ponctuation pour la recherche
$carToReplace = array('.', ',', '?', '!', ':', ';', '"', '...', '(', ')', "'");
$textToSearch = str_replace($carToReplace, "", $text);
$tabTextToSearch = explode(" ", $textToSearch);
$tabText = explode(" ", $text);
$resSearch = array_search($wordSearch, $tabTextToSearch);
if ($resSearch === false) {
return false;
}
$indexFirstWord = $resSearch - $nbWords;
if ($indexFirstWord < 0) {
$indexFirstWord = 0;
}
$before = array_slice($tabText, $indexFirstWord, $nbWords);
$after = array_slice($tabText, $resSearch + 1, $nbWords);
return array(
implode(' ', $before),
'<strong>'.$wordSearch.'</strong>',
implode(' ', $after),
);
}
$text = "Voici un texte de texte, dans lequel on va chercher un mot en particulier et qui affichera (ceci est un test) les '10 mots' qui se situe avant et après ce mot, pour voir comment c'est facile d'utiliser les tableaux en php.";
$wordSearch = "après";
$resSearch = search($wordSearch, $text);
if ($resSearch !== false) {
echo implode(" ",$resSearch);
} else {
echo "Mot non trouvé dans la chaîne";
}
////////
function getExcerpt($needle, $str) {
$pattern = '~((?:\p{Xan}+\P{Xan}+){0,10}?)(' . preg_quote($needle, '~') . ')((?:\P{Xan}+\p{Xan}+){0,10})~i';
if (preg_match($pattern, $str, $match))
return $match[1] . '<strong>' . $match[2] . '</strong>' . $match[3];
else
return false;
}
getExcerpt($texte,$wordSearch); |
Partager