2012-03-25 16 views
0

我用下面來檢查拼寫單詞輸入到搜索:「你的意思是」谷歌的搜索類型,但是,字符串,而不是隻是一個字

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的

,但如果我輸入「ipoad 4G」它認爲拼寫正確。

因此,我認爲,爆炸的字符串,並逐字地去做?

但是,當我嘗試這個它根本不工作 - 有沒有更好的方法?

這裏有我想要的代碼:

$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">'; 
} 
+2

定義「不起作用」。 – 2012-03-25 16:17:27

+0

我是否有這樣的權利:您是在刮Google的搜索結果來做自己的自動更正?這很搞笑。這是正常的嗎? – 2012-03-25 16:27:11

+0

是的,它與使用雅虎自動提速API相同,但更快恕我直言 - 我認爲哈哈 – 2012-03-25 16:30:51

回答

0

在你的foreach循環你在覆蓋每次迭代$word變量。所以在你的檢查中,你只是檢查最後一個單詞拼寫是否正確。你可以使用concat操作符來解決這個問題。

$res = $gdym->autocorrect($f); 
if ($res === false) { 
    $word = $res; 
    break; 
} else { 
    $word .= " " . $res; 
} 
+0

@弗洛如果我嘗試這與'ipoad 4g'它什麼都沒有返回 – 2012-03-25 16:35:56

+0

你什麼意思都沒有?爲$ res添加一些var_dump()調用,以便您知道Google爲每個部件返回的內容。 – flo 2012-03-25 16:38:32

+0

這不完全正確的答案,但它給了我想法,能夠解決這個問題,所以感謝。 – 2012-03-26 07:50:47

相關問題