PHP中的部分字符串用于匹配字符串

时间:2013-07-29 17:15:16

标签: php string

我正在构建一个具有字符串输入的小应用程序。我也有一个单词数组,如果数组中的任何完整值与输入字符串部分匹配,我想匹配。例如:

Array('London Airport', 'Mancunian fields', 'Disneyland Florida') 

如果用户输入“美国佛罗里达州迪士尼乐园”或“美国佛罗里达州迪斯尼乐园”,我想返回一个匹配。

任何帮助都将受到高度赞赏。提前谢谢。

3 个答案:

答案 0 :(得分:1)

要搜索的数据:

<?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开头无关。

答案 1 :(得分:0)

function isInExpectedPlace($inputPlace) {
    $places = array('London Airport', 'Mancunian fields', 'Disneyland Florida');
    foreach($places as $place) {
        if(strpos($inputPlace, $place) !== false)
            return true;
        }
    }
    return false;
}

答案 2 :(得分:0)

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);