我正在构建具有字符串输入的小型应用程序。我还有一个单词数组,如果数组中的任何完整值与输入字符串部分匹配,我想匹配。例子:
Array('London Airport', 'Mancunian fields', 'Disneyland Florida')
如果用户键入“美国佛罗里达迪士尼乐园”或只是“美国佛罗里达迪士尼乐园”,我想返回匹配项。
任何帮助将不胜感激。提前致谢。
要搜索的数据:
<?php
$data = array(
0 => 'London Airport',
1 => 'Mancunian fields',
2 => 'Disneyland Florida'
);
搜索功能:
<?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;
}
结果:
<?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');
搜索功能:
<?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;
}
结果:
<?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');
如您所见, id 用户搜索的顺序以及字符串是否以 . 开头都无关紧要Disneyland
。
function isInExpectedPlace($inputPlace) {
$places = array('London Airport', 'Mancunian fields', 'Disneyland Florida');
foreach($places as $place) {
if(strpos($inputPlace, $place) !== false)
return true;
}
}
return false;
}
PHP 5.3+ 用于匿名函数的使用:
<?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);