Skip to content

Instantly share code, notes, and snippets.

@igor822
Last active August 29, 2015 14:03
Show Gist options
  • Save igor822/f3e62ba7106d1d8be464 to your computer and use it in GitHub Desktop.
Save igor822/f3e62ba7106d1d8be464 to your computer and use it in GitHub Desktop.
Contador de palavras
<?php
function removerAcento($string) {
$from = "áàãâéêíóôõúüçÁÀÃÂÉÊÍÓÔÕÚÜÇ";
$to = "aaaaeeiooouucAAAAEEIOOOUUC";
$keys = array();
$values = array();
preg_match_all('/./u', $from, $keys);
preg_match_all('/./u', $to, $values);
$mapping = array_combine($keys[0], $values[0]);
return strtr($string, $mapping);
}
class ContaPalavras {
private $textos;
private $listPalavras;
private $palavras;
private $total = 0;
public function __construct($textos) {
$this->textos = $textos;
if (is_array($this->textos)) {
foreach ($this->textos as $texto) {
$this->separaPalavras($texto);
$this->contador(count($this->listaPalavras) - 1);
}
} else {
throw new Exception('É necessário que os textos estejam em array');
}
}
private function separaPalavras($texto) {
$palavras = explode(' ', str_replace("\n", ' ', $texto));
$this->listaPalavras = array_map(function($k) {
if ($k != '') return removerAcento($k);
}, $palavras);
}
private function contar($n = 0) {
$palavra = $this->listaPalavras[$n];
$this->palavras[$palavra] = !empty($this->palavras[$palavra]) ? $this->palavras[$palavra]+1 : 1;
$this->total++;
if ($n == 0) return $this->palavras;
$this->contar($n - 1);
}
public function pegaPalavras() {
arsort($this->palavras);
$arr = array('total_palavras' => $this->total, 'palavras' => $this->palavras);
return json_encode($arr);
}
}
if ($_POST) {
try {
$contaPalavras = new ContaPalavras($_POST['textos']);
echo $contaPalavras->pegaPalavras();
} catch (Exception $e) {
echo $e->getMessage();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment