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

从PHP中的字符串中提取数组中预定义短语的精确匹配,php,arrays,string,Php,Arrays,String,需要$new\u string输出new York NY,但我得到了new 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) !== fal

需要
$new\u string
输出
new York NY
,但我得到了
new 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;

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

纽约州纽约市的
纽约州纽约市的
都可以在
$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;
    }
}

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

纽约州纽约市的
纽约州纽约市的
都可以在
$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;
    }
}
stripos(“我住在纽约”,“纽约纽约”)
stripos(“我住在纽约”,“纽约纽约”)
都是
!==错误

您可以创建一个只支持较长文本的循环

$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);
preg_match/如果可选分隔符
stripos(“我住在纽约”、“纽约纽约”)
stripos(“我住在纽约”、“纽约纽约”)
都是
!==错误

您可以创建一个只支持较长文本的循环

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

preg_match/If可选分隔符

尝试从单行输入字段中提取预定义的美国位置短语。尝试从单行输入字段中提取预定义的美国位置短语。这适用于“我住在纽约”、“我住在纽约”、“我住在怀俄明州”但对“我住在明尼苏达州怀俄明州”无效谢谢你的帮助。更新的代码现在适用于“我住在明尼苏达州怀俄明州”,但不适用于“我住在纽约”。你帮助我走上了正确的道路,希望我能从这里找到答案。不确定你所说的失败是什么意思。。。从这里开始,如果您为$短语(如“10016”)和$string(如“I live in New York NY 10016”)添加另一个值,则会在$matches中添加“York NY NY”这是为“I live in New York NY NY NY”、“I live in York NY”、“I live in怀俄明州MI”而设计的,但为“I live in怀俄明州明尼苏达州”而设计的,谢谢您的帮助。更新的代码现在适用于“我住在明尼苏达州怀俄明州”,但不适用于“我住在纽约”。你帮助我走上了正确的道路,希望我能从这里找到答案。不确定你所说的失败是什么意思。。。当您向$phrases(如“10016”)和$string(如“I live in New York NY 10016”)添加另一个值时,它将向$matches(如$matches)添加“York NY”(纽约市纽约市纽约市纽约市纽约市纽约市纽约市纽约市纽约市)时,从这里可以完美地工作