我使用以下内容来检查输入搜索的单词的拼写:
class GDYM {
public $language = 'en';
/**
* Google Search for PDA (because it's smaller)
*
* @var string
*/
private $_url = 'http://google.com/pda?q=%s&hl=%s';
/**
* Use Google to find out if the entered query is correctly spelled
*
* @param string $query
* @return mixed
*/
public function autocorrect( $query)
{
// build url
$url = sprintf($this->_url, urlencode($query), $this->language);
// store html output
$source = file_get_contents( $url);
// strip other html data
preg_match("'<b><i>(.*?)</i></b></a>'si", $source, $match);
return (isset( $match[0]) ) ? strip_tags($match[0]) : FALSE;
}
}
然后我使用:
$word = $gdym->autocorrect($_POST['word']);
所以,如果我输入"ipoad",它会正确地认为我的意思是"ipad"
但如果我输入"ipoad4g",它会认为拼写正确。
所以我想,把字符串分解,然后一个字一个字地做?
但当我尝试这种方法时,它根本不起作用——有更好的方法吗?
这是我正在尝试的代码:
$string = $_POST['word'];
$pieces = explode(" ", $string);
foreach($pieces as $f ){
$word = $gdym->autocorrect($f);
}
if($word == false)
{
echo '<span class="response">The word "'. $string .'" is correctly spelled</span>';
}
else
{
echo '<span class="response">Response from Google autocorrection: ' . $word.'<span class="response">';
}
在foreach循环中,您将在每次迭代中覆盖$word
变量。所以在你的检查中,你只是在检查最后一个单词拼写是否正确。您可以使用concat运算符来解决此问题。
$res = $gdym->autocorrect($f);
if ($res === false) {
$word = $res;
break;
} else {
$word .= " " . $res;
}