需要$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;
答案 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 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;
}
}