Reputation: 117
I am building small application which has an input for a string. I also have an array of words and I want to match if any full value in the array matches partially with the input string. Example:
Array('London Airport', 'Mancunian fields', 'Disneyland Florida')
If a user types 'Disneyland Florida in USA' or just 'Disneyland Florida, USA' I want to return a match.
Any help would be highly appreciated. Thanks in advance.
Upvotes: 0
Views: 720
Reputation: 1265
Data to search in:
<?php
$data = array(
0 => 'London Airport',
1 => 'Mancunian fields',
2 => 'Disneyland Florida'
);
Searching function:
<?php
/**
* @param array $data
* @param string $what
* @return bool|string
*/
function searchIn($data, $what) {
foreach ($data as $row) {
if (strstr($what, $row)) {
return $row;
}
}
return false;
}
Results:
<?php
// Disney Florida
echo searchIn($data, 'Disneyland Florida in USA');
// Disney Florida
echo searchIn($data, 'Disneyland Florida, USA');
// false
echo searchIn($data, 'whatever Florida Disneyland');
echo searchIn($data, 'No match');
echo searchIn($data, 'London');
Searching function:
<?php
/**
* @param array $data
* @param string $what
* @return int
*/
function searchIn($data, $what) {
$needles = explode(' ', preg_replace('/[^A-Za-z0-9 ]/', '', $what));
foreach ($data as $row) {
$result = false;
foreach ($needles as $needle) {
$stack = explode(' ', $row);
if (!in_array($needle, $stack)) {
continue;
}
$result = $row;
}
if ($result !== false) {
return $result;
}
}
return false;
}
Results:
<?php
// Disneyland Florida
echo searchIn($data, 'Disneyland Florida in USA');
// Disneyland Florida
echo searchIn($data, 'Disneyland Florida, USA');
// Disneyland Florida
echo searchIn($data, 'whatever Florida Disneyland');
// false
echo searchIn($data, 'No match');
// London Airport
echo searchIn($data, 'London');
As you can see, id doesn't matter in what order user is searching and whether or not the string starts with Disneyland
.
Upvotes: 1
Reputation:
PHP 5.3+ for the use of the anonymous function:
<?php
$places = array('London Airport', 'Mancunian fields', 'Disneyland Florida');
$search = 'Disneyland Florida in USA';
$matches = array_filter($places, function ($place) use ($search) {
return stripos($search, $place) !== false;
});
var_dump($matches);
Upvotes: 0
Reputation: 1262
function isInExpectedPlace($inputPlace) {
$places = array('London Airport', 'Mancunian fields', 'Disneyland Florida');
foreach($places as $place) {
if(strpos($inputPlace, $place) !== false)
return true;
}
}
return false;
}
Upvotes: 0