2

文字列の複数の値をチェックするために使用できる関数を構築しようとしています。値を配列に分割し、配列をループして、for each ループを使用して文字列に対して値をチェックしようとしましたが、期待される結果が得られません。以下の関数、いくつかの例、および期待される結果を参照してください。

関数

function find($haystack, $needle) {
    $needle = strtolower($needle);
    $needles = array_map('trim', explode(",", $needle));

    foreach ($needles as $needle) {
        if (strpos($haystack, $needle) !== false) {
            return true;
        }
    }

    return false;
}

例 1

$type = 'dynamic'; // on a dynamic page, could be static, general, section, home on other pages depending on page and section

if (find($type, 'static, dynamic')) {
    // do something
} else {
    // do something
}

結果

これは、$type に static または dynamic が含まれているかどうかの条件をキャッチし、ページに応じて同じコードを実行する必要があります。

例 2

$section = 'products labels'; // could contain various strings generated by site depending on page and section

if (find($section, 'products')) {
    // do something
} elseif (find($section, 'news')) {
    // do something
} else {
    // do something
}

結果

これは、ニュース セクション内のページの製品セクション 'ニュース' 内のページで $section に 'products' が含まれている場合に特に条件をキャッチする必要があります。

--

目的の結果を返すのに信頼性がないようで、その理由がわかりません! どんな助けでも大歓迎です!

4

3 に答える 3

3

このようなものかもしれません

function strposa($haystack, $needles=array(), $offset=0) {
    $chr = array();
    foreach($needles as $needle) {
            $res = strpos($haystack, $needle, $offset);
            if ($res !== false) $chr[$needle] = $res;
    }
    if(empty($chr)) return false;
    return min($chr);
}

その後

$string = 'Whis string contains word "cheese" and "tea".';
$array  = array('burger', 'melon', 'cheese', 'milk');

if (strposa($string, $array, 1)) {
    echo 'true';
} else {
    echo 'false';
}

これはチーズのおかげで真実になります

于 2013-04-07T20:53:46.100 に答える
1

find便利な2way がここにある理由

var_dump(find('dynamic', 'static, dynamic')); // expect true
var_dump(find('products labels', 'products')); // expect true
var_dump(find('foo', 'food foor oof')); // expect false

使用する機能

function find($str1, $str2, $tokens = array(" ",",",";"), $sep = "~#") {
    $str1 = array_filter(explode($sep, str_replace($tokens, $sep, strtolower($str1))));
    $str2 = array_filter(explode($sep, str_replace($tokens, $sep, strtolower($str2))));
    return array_intersect($str1, $str2) || array_intersect($str2, $str1);
}
于 2013-04-07T21:05:17.520 に答える
1

どうですか:

str_ireplace($needles, '', $haystack) !== $haystack;
于 2014-12-31T17:39:15.983 に答える