Back to blog

Do spelling using google spell checker

If you have a user input that may contains some error you can try to check the spelling using Google…

If you have a user input that may contains some error you can try to check the spelling using Google Spelling Suggestion service (there is an api and you have to register to have an api key to use their web services).

But you can obtain the same result searching the Google search engine and parsing the html code to find the link after the phrase: “Did you mean“. You can think at this code as a mini web bot spell checker.

This code works in any language, it finds the anchor tag that has the classname set to “spell”:

DEMO

echo doGoogleSpelling("wokipedia");  //returns "wikipedia"

function doGoogleSpelling($q) {

	// grab google page with search
	$web_page = file_get_contents( "http://www.google.it/search?q=" . urlencode($q) );
	
	// put anchors tag in an array
	preg_match_all('#<a([^>]*)?>(.*)</a>#Us', $web_page, $a_array);
	for($j=0;$j<count($a_array[0]);$j++) {

		// find link with spell suggestion and return it
		if(stristr($a_array[0][$j],"class=spell")) return strip_tags($a_array[0][$j]);

	}

	return "";
}

Canonical URL