1

需要$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;
4

2 回答 2

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

于 2012-11-13T00:45:52.210 回答
0

那是因为它正在查看是否$phrase在您的$string.

New York NY和都York 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;
    }
}
于 2012-11-13T00:23:15.723 回答