【问题标题】:php check string for multiple valuesphp检查多个值的字符串
【发布时间】:2013-03-29 20:33:34
【问题描述】:

我正在尝试构建一个函数,我可以用它来检查一个字符串的多个值,这是一种在干草堆中的通用查找针的函数。我已将值拆分为一个数组,并尝试遍历数组并使用 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 是包含静态还是动态的条件,并根据页面运行相同的代码。

示例 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 在新闻部分的页面上的产品部分的“新闻”页面上包含“产品”,这应该特别捕捉条件。

--

返回所需结果似乎不可靠,并且无法弄清楚原因!非常感谢任何帮助!

【问题讨论】:

  • 您的strtolower 调用由于下一行的拼写错误而最终没有执行任何操作,但此代码仍应按给定的方式工作——至少对于这两种特殊情况。
  • 感谢指出,我已经修改了上面的函数。正如您所说,我相信该函数可以正常工作,但我可能在代码中使用的一些 if / elseif / else 语句中纠结并犯了错误。

标签: php arrays string search if-statement


【解决方案1】:

可能是这样的

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';
}

因为奶酪,这将是真的

【讨论】:

  • 我知道,offset 选项有什么作用?
  • 偏移量指定您希望在字符串中的哪个点开始搜索。在这种情况下,我们希望从头开始搜索。
【解决方案2】:

为什么这里有一个可以派上用场的 2way find

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

【讨论】:

    【解决方案3】:

    怎么样:

    str_ireplace($needles, '', $haystack) !== $haystack;
    

    【讨论】:

      猜你喜欢
      • 2016-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-11
      • 2013-02-18
      • 2021-01-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多