I have the following HTML with jQuery:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
<script type="text/javascript" src="../scripts/jquery-2.1.4.min.js"></script>
<link href="../scripts/ui/jquery-ui.min.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="../scripts/ui/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function() {
$("#acInput").autocomplete({
source: "autocomplete.php"
})
})
</script>
</head>
<body>
<div class="ui-widget">
<label for="acInput">Flower Name: </label><input type="text" name="acInput" id="acInput">
</div>
</body>
</html>
and I want to create a PHP file (autocomplete.php which would be in the same directory) that will search through array and return response:
I've tried the following way:
<?php
$flowers = ["Aster", "Daffodil", "Rose","Peony", "Primula", "Snowdrop", "Poppy", "Primrose", "Petuna", "Pansy"];
$matches = [];
if (isset($_GET["term"])) {
$term = trim($_GET["term"]); // do I need to remove/strip tags or escape it and what is the best way?
if (!empty($term)) {
$pattern = '/^'+$term+'/';
foreach ($flowers as $cvet) {
preg_match($pattern, $cvet, $matches);
}
echo json_encode($matches);
}
}
But it doesn't work. I assume that the problem has to do with $pattern or preg_match, since this is the first time I use regular expression with PHP?
EDIT: What I want is to check:
1. Are there values in the array $flowers that are equal to $term OR start with $term;
2. Are there values in the array $flowers containing $term.
Return all of these $flowers array values (elements) to jQuery autocomplete and display them as suggestions. Thanks!