First of all, I'm new to development so need a little hand holding.
I've built a simple search field (with suggestions) and send users to a relevant landing page on an array match. I return an error message if the search isn't relevant. However, my code relies on the user clicking a suggestion or typing the whole word in the search field. Therefore, the usability is poor.
The code below will highlight my problem. Ideally, I need to match a field input 'br' to 'bristol' (as per my suggestion to the user). I think the solution is http://php.net/manual/en/function.levenshtein.php but I'm having problems implementing (like I said, I'm new). I would appreciate any guidance.
Thanks heaps for your time!
<?php
$counties = array("Avon",
"Bristol",
"Bedfordshire",
"Berkshire",
"Buckinghamshire"
);
if (in_array(strtolower($_GET["my_input"]), array_map('strtolower', $counties)))
{ header('Location: http://domain.co.uk/county/'.strtolower(str_replace(' ', '-', $_GET['my_input'])));
}
else
{
header('Location: ' . $_SERVER['HTTP_REFERER'] . "?message=tryagain");
exit;
}
?>
Could be optimized but in general:
foreach(array_map('strtolower', $counties) as $county) {
if(substr($county, 0, strlen($_GET["my_input"])) == strtolower($_GET["my_input"])) {
header('Location: http://domain.co.uk/county/'.str_replace(' ', '-', $county));
exit;
}
}
header('Location: ' . $_SERVER['HTTP_REFERER'] . "?message=tryagain");
exit;
$counties
and compare the $_GET["my_input"]
to the same number of beginning characters in $county
$county
in the header and not $_GET["my_input"]
Obviously if the user enters Be
then Bedfordshire
being the first entry will be chosen. So long as your "suggestions" are in the same order it should work fine.
In case the user enters a trailing space or something, maybe trim()
:
if(substr($county, 0, strlen(trim($_GET["my_input"]))) == strtolower(trim($_GET["my_input"]))) {