我正在構建一個小型應用程序,它有一個字符串輸入。如果數組中的任何完整值與輸入字符串部分匹配,我也會有一組單詞。例如:PHP中部分字符串匹配字符串
Array('London Airport', 'Mancunian fields', 'Disneyland Florida')
如果用戶輸入「佛羅里達州迪斯尼樂園在美國」或只是「迪斯尼樂園,美國佛羅里達州」我要返回匹配。
任何幫助將不勝感激。提前致謝。
我正在構建一個小型應用程序,它有一個字符串輸入。如果數組中的任何完整值與輸入字符串部分匹配,我也會有一組單詞。例如:PHP中部分字符串匹配字符串
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');
正如你所看到的,用戶搜索的順序以及該字符串是否以Disneyland
開頭並不重要。
感謝您的時間和解決方案。您的解決方案匹配任何關鍵字,我想要的只是陣列中的完全匹配。即如果用戶輸入「佛羅里達州迪士尼樂園」或「美國佛羅里達州迪士尼樂園」這兩種情況都會返回true,但如果用戶輸入「USA Disneyland NOT Florida」或「Florida Disneyland」這兩種情況都會返回錯誤。 – aniga
所以,我用大炮殺死了一隻蒼蠅;)應該返回錯誤的輸入:「佛羅里達迪士尼樂園」,「佛羅里達州迪士尼樂園」,「迪斯尼樂園佛羅里達東西」,「迪士尼樂園」。對? – TheFrost
正確。只有當數組數據上的完整字符串與用戶輸入的部分或全部字符串匹配時才返回true。再次感謝你的時間。 – aniga
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);
你已經試過了什麼? – BenM
我已經嘗試了in_array,它只返回真正的全字符匹配 – aniga