New file |
0,0 → 1,97 |
<?php |
class Surligneur { |
private $texte = ''; |
private $texteSansAccent = ''; |
private $tags = array(); |
private $nbreSurlignageMaxParMot = 1; |
private $nbreSurlignageCourant = 0; |
|
public function __construct($texte = null, $surlignageMaxParMot = null) { |
if (is_null($texte) == false) { |
$this->setTexte($texte); |
} |
if (is_null($surlignageMaxParMot) == false) { |
$this->setNbreMaxSurlignageParMot($surlignageMaxParMot); |
} |
} |
|
public function setTexte($txt) { |
$this->texte = $txt; |
} |
|
public function setNbreMaxSurlignageParMot($nbre) { |
$this->nbreSurlignageMaxParMot = $nbre; |
} |
|
function supprimerAccents($chaine){ |
return strtr($chaine,array('à' => 'a','á' => 'a','â' => 'a','ã' => 'a','ä' => 'a', |
'ç' => 'c', |
'è' => 'e','é' => 'e','ê' => 'e','ë' => 'e', |
'ì' => 'i','í' => 'i','î' => 'i','ï' => 'i', |
'ñ' => 'n', |
'ò' => 'o', 'ó' => 'o' , 'ô' => 'o', 'õ' => 'o', 'ö' => 'o', |
'ù' => 'u', 'ú' => 'u', 'û' => 'u', 'ü' => 'u', |
'ý' => 'y', 'ÿ' => 'y')); |
} |
|
public function surlignerMots($mots) { |
$this->verifierTableauDeMots($mots); |
$this->texte = preg_replace_callback('`<[^>]+>`', array($this, 'sauverTags'), $this->texte); |
foreach ($mots as $mot) { |
$this->initialiserNbreSurlignageCourant(); |
$this->texte = $this->surlignerMot($mot); |
} |
$this->texte = preg_replace_callback('`<([0-9]+)>`', array($this, 'restaurerTags'), $this->texte); |
return $this->texte; |
} |
|
private function verifierTableauDeMots($mots) { |
if (is_array($mots) === false) { |
$message = "Surligneur::surlignerMots() n'accepte que les tableaux de mots en argument"; |
throw new InvalidArgumentException($message); |
} else { |
if (count($mots) == 0) { |
$message = "Surligneur::surlignerMots() n'accepte que des tableaux contenant au moins un mot"; |
throw new LengthException($message); |
} |
} |
} |
|
private function sauverTags($match) { |
$i = count($this->tags); |
$this->tags[$i] = $match[0]; |
return '<'.$i.'>'; |
} |
|
private function initialiserNbreSurlignageCourant() { |
$this->nbreSurlignageCourant = 0; |
} |
|
private function surlignerMot($mot) { |
$positionDebutMot = stripos($this->texte, $mot); |
$longueurMot = strlen($mot); |
$surlignage = $this->texte; |
if ($positionDebutMot !== false) { |
$this->nbreSurlignageCourant++; |
if ($this->nbreSurlignageCourant <= $this->nbreSurlignageMaxParMot) { |
$debut = substr($this->texte, 0, $positionDebutMot); |
$milieu = substr($this->texte, $positionDebutMot, $longueurMot); |
$this->texte = substr($this->texte, $positionDebutMot + $longueurMot); |
$fin = $this->surlignerMot($mot); |
$surlignage = $debut.$this->sauverTagSurlignage($milieu).$fin; |
} |
} |
return $surlignage; |
} |
|
private function sauverTagSurlignage($motTrouve) { |
$i = count($this->tags); |
$this->tags[$i] = '<span class="surlignage">'.$motTrouve.'</span>'; |
return '<'.$i.'>'; |
} |
|
private function restaurerTags($match) { |
return $this->tags[$match[1]]; |
} |
} |
?> |