从PHP中的字符串中提取数组中预定义短语的精确匹配

时间:2012-11-13 00:19:20

标签: php arrays string

需要$new_string输出New York NY,但需要New York NY York NY

$phrases = array("New York NY","York NY","Wyoming MI","Wyoming Minnesota");
$string = ("I live in New York NY");

$matches = array();
foreach($phrases as $phrase) {
    if(stripos($string,$phrase) !== false){
        $matches[] = $phrase;
    }
}

$new_string = implode(" ",$matches);

echo $new_string;

2 个答案:

答案 0 :(得分:1)

stripos("I live in New York NY", "New York NY")stripos("I live in New York NY", "York NY")都是!=== false

您可以创建仅支持较长文本的循环

$phrases = array("New York NY","York NY","Wyoming MI","Wyoming Minnesota");
$string = ("I live in Wyoming Minnesota");
$matches = array();
foreach ( $phrases as $phrase ) {
    $phrase = preg_quote($phrase, '/');
    if (preg_match("/\b$phrase\b/i", $string)) {
        $matches[] = $phrase;
    }
}
echo "<pre>";
print_r($matches);

输出

Array
(
    [0] => Wyoming Minnesota
)

preg_match /如果是可选的分隔符@DaveRandom

答案 1 :(得分:0)

那是因为它正在查看您的$phrase中是否找到$string

New York NYYork NY都位于$string,因此它们都被添加到$matches


我不确定“大图”是什么,但您可能希望将$string分成两部分,然后仅比较位置:

$places = array("New York NY","York NY","Wyoming MI","Wyoming Minnesota");
$strLive = "I live in ";
$strLoc = "New York NY";

$matches = array();
foreach($places as $place) {
    if($strLoc == $place){
        $matches[] = $place;
    }
}