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 NYYork NYは両方$stringともにあるので、両方ともに追加され$matchesます。


「全体像」が何であるかはわかりませんが、$string2つの部分に分割して、場所のみを比較することをお勧めします。

$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 に答える