Skip to content

Instantly share code, notes, and snippets.

@redpanda
Created April 24, 2012 13:04
Show Gist options
  • Select an option

  • Save redpanda/2479470 to your computer and use it in GitHub Desktop.

Select an option

Save redpanda/2479470 to your computer and use it in GitHub Desktop.
hunspell
<?php
$h = new Hunspell\Hunspell('/usr/bin/hunspell');
$h->check("Hello world");
var_dump($h->getErrors(function ($row) {
return $row['word'];
}));
/*array(0) {
}*/
$h->check("Helloo world");
var_dump($h->getErrors(function ($row) {
return $row['suggestions'];
}));
/*array(1) {
[0]=>
array(9) {
[0]=>
string(5) "Hello"
[1]=>
string(6) "Hellos"
[2]=>
string(7) "Hello o"
[3]=>
string(7) "Hellion"
[4]=>
string(8) "Hellhole"
[5]=>
string(6) "Heller"
[6]=>
string(6) "Hell's"
[7]=>
string(6) "Helios"
[8]=>
string(4) "Hell"
}
}*/
$h->setLanguage('fr_FR');
$h->check("Boonjour le monde");
var_dump($h->getErrors());
/*array(1) {
[0]=>
array(4) {
["word"]=>
string(8) "Boonjour"
["row"]=>
int(1)
["column"]=>
int(1)
["suggestions"]=>
array(5) {
[0]=>
string(7) "Bonjour"
[1]=>
string(8) "Boulgour"
[2]=>
string(8) "Bourgeon"
[3]=>
string(10) "Baïkonour"
[4]=>
string(10) "Bourdonné"
}
}
}*/
<?php
namespace Hunspell;
class Hunspell
{
private $path;
private $language;
private $errors;
public function __construct($path, $language = 'en_US')
{
$this->setPath($path);
$this->setLanguage($language);
}
public function setPath($path)
{
if (!file_exists($path)) {
throw new \RuntimeException(sprintf('The hunspell binary "%s" does not exists.', $this->path));
}
$this->path = $path;
}
public function getPath()
{
return $this->path;
}
public function setLanguage($language)
{
$this->language = $language;
}
public function getLanguage()
{
return $this->language;
}
public function check($str)
{
$output = shell_exec(sprintf('echo "%s" | %s -d %s', $str, $this->path, $this->language));
if (is_null($output)) {
throw new \RuntimeException();
}
$this->errors = array();
$lines = explode(PHP_EOL, $output);
foreach ($lines as $row => $line) {
if (preg_match('/^\& (.*?) (\d+) (\d+): (.*)/', $line, $matches)) {
$this->errors[] = array(
'word' => $matches[1],
'row' => $row,
'column' => intval($matches[3])+1,
'suggestions' => explode(', ', $matches[4]),
);
}
}
}
public function getErrors(\Closure $callback = null)
{
if (is_null($callback)) {
return $this->errors;
}
return array_map($callback, $this->errors);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment