如何找到一个字符串的多个子字符串,但如果找不到多个,仍然返回找到的子字符串数


How to find multiple substrings of a string, but if multiple are not found, still return however many substrings were found

好的,这样解释更容易。

我有一个变量:

 $string

我也有子字符串变量:

$sub1, $sub2, $sub3, $sub4

如果找到任何子字符串变量,我需要回显$string。如果找到多个子字符串变量,则包含。

我用这个来查找子字符串:

    if (strpos($filename, $clothes) > 0 {
        echo $string
    }

最让我困惑的是,如果有全部或部分子字符串,则返回$string。

首先,为了简单起见,将这些子字符串变量视为一个数组。现在,代码可能是这样的,

function doIt($string, $sub_strings){
    foreach($sub_strings as $substr){
        if(strpos($string, $substr) !== FALSE)
        {
          return $string; // at least one of the needle strings are substring of heystack, $string
        }
    }
   return ""; // no sub_strings is substring of $string.
}

并且要使用此功能,

echo doIt($string,array($str1,$str2,$str3,$str4));

感谢Orangepill!

只需创建一个函数,根据字符串测试数组中的每个值,如果找到任何值,则返回true。

function findOneOf(array $terms, $string){
      foreach ($terms as $term){
          if (strpos($string, $term) !== FALSE){
              return true;
          }
      }
      return false;
}

然后你可以像一样进行测试

if (findOneOf(array($sub1, $sub2, $sub3,$sub4), $string)){
     echo $string;
}