Skip to content

Instantly share code, notes, and snippets.

@hobodave
Created April 23, 2009 08:05
Show Gist options
  • Select an option

  • Save hobodave/100387 to your computer and use it in GitHub Desktop.

Select an option

Save hobodave/100387 to your computer and use it in GitHub Desktop.
<?php
/**
* SpellCheck
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://hobodave.com/license.txt
*
* @package SpellCheck
* @copyright Copyright (c) 2008-2009 David Abdemoulaie (http://hobodave.com/)
* @license http://hobodave.com/license.txt New BSD License
*/
class SpellCheck
{
protected function __construct()
{
$this->_getDict();
}
/**
* @param string $word
* @return bool
*/
public function check($word)
{
$dict = $this->_getDict();
return pspell_check($dict, $word);
}
/**
* @param string $word
* @return array
*/
public function suggest($word)
{
$dict = $this->_getDict();
return pspell_suggest($dict, $word);
}
/**
* @param string $text
* @return array
*/
public function checktext($text)
{
$dict = $this->_getDict();
$matches = array();
$result = array(
'c' => array()
);
preg_match_all(
'/\w+/',
$text,
$matches,
PREG_OFFSET_CAPTURE|PREG_PATTERN_ORDER);
foreach($matches[0] as $match) {
if (pspell_check($dict,$match[0])) {
continue;
}
$suggestions = pspell_suggest($dict,$match[0]);
$correction = array(
'o' => $match[1],
'l' => strlen($match[0]),
't' => array_slice($suggestions, 0, 5)
);
$result['c'][] = $correction;
}
return $result;
}
protected function _getDict()
{
if ($this->_dict === null) {
$this->_dict = pspell_new('en', '', '', '', PSPELL_FAST);
}
return $this->_dict;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment