HTML
<form action=""><input type="text" name="word" id="word"></form>
<div id="auto"></div>
JS
$(function(){
$('#word').keyup(function(e){
var input = $(this).val();
$.ajax({
type: "get",
url: "autocomplete.php",
data: {word: input},
async: true,
success: function(data){
var outWords = $.parseJSON(data);
$('#auto').html('');
for(x = 0; x < outWords.length; x++){
$('#auto').prepend('<div>'+outWords[x]+'</div>'); //Fills the #auto div with the options
}
}
})
})
});
Don't forget to link jQuery
...
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
N.B.
You would need to do something like add an onclick
event to the child div
s of #auto
to replace the contents of #word
(the input field).
PHP
$array = array('microsoft','micromax', 'miniclip','michael jackson','million','milky way');
$input = urldecode($_GET['word']); //Get input word/phrase (decode in case of spaces etc.)
$length = strlen($input); //Get length of input word
// $min = $length - 1; //Length of word - 1
// $max = $length + 1; //Length of word + 1
$returned = preg_grep('/^(['.$input.']{'.$length.'}.*)$/i', $array); //Find matches in $array and return as array
$returned = array_values($returned); //Re-index from 0
echo json_encode($returned); //Returm json string to ajax call
Regex
/^([$input]{$length}.*)$/i
-
/
=> Starting delimter
-
^
=> Start of string
-
(
=> Start a capture group
-
[
=> Start a character class
-
$input
=> Add the input word to the character class
-
]
=> End the character class (4)
-
{$length}
=> Set length of string to match character class against (length of input word)
-
.*
=> Match any following characters 0 or more times
-
)
=> End capture group (3)
-
$
=> Match end of string
-
/
=> Ending delimeter
-
i
=> Modifier for case insensitivity
Min/Max
I have included the commented $min
and $max
variables... An added feature that I thought you might like... You would implement them by changing:
{'.$length.'} <-- Change this
{'.$min.','.$max.'} <--To that
{'.$length.','.$max.'} <-- Or that (or another combination)
Example
An example might best show how this works...
Suppose an auto correct array of:
$array = array('loser', 'loses', 'losing');
and an input of:
lose
Currently ({'.$length.'}
) the code will return:
loser
loses
But if you change it to {'.$min.','.$max.'}
(and uncomment $min
/ $max
); it will return:
losing
loser
loses