字符串包含数组中的任何项目(不区分大小写)

问题描述 投票:0回答:15

我如何检查

$string
是否包含数组中表达的任何项目?

$string = 'My nAmE is Tom.';
$array = array("name","tom");
if(contains($string,$array))
{
// do something to say it contains
}

有什么想法吗?

php string arrays contains
15个回答
111
投票

我不认为有一个内置函数可以处理你想要的事情。不过,您可以轻松编写

contains()
函数:

function contains($str, array $arr)
{
    foreach($arr as $a) {
        if (stripos($str,$a) !== false) return true;
    }
    return false;
}

25
投票

这就是你想要的吗?我希望代码能够编译:)

$string = 'My nAmE is Tom.';
$array = array("name","tom");
if(0 < count(array_intersect(array_map('strtolower', explode(' ', $string)), $array)))
{
  //do sth
}

18
投票

使用已接受的答案:

$string = 'My nAmE is Tom.';
$array = array("name","tom");
if(0 < count(array_intersect(array_map('strtolower', explode(' ', $string)), $array)))
{
  //do sth
}

顺便说明一下,if 语句可以更改为:

if(0 < count(array_intersect(explode(' ', strtolower($string)), $array)))

因为实际上没有必要使用 array_map 将

strtolower
应用于每个元素。而是将其应用于初始字符串。


10
投票

contains 函数的另一种解决方法

function contains($string, $array, $caseSensitive = true)
{
    $strippedString = $caseSensitive ? str_replace($array, '', $string) : str_ireplace($array, '', $string);
    return $strippedString !== $string;
}

PS。至于我,我只是用它,没有功能...

if (str_replace($array, '', $string) !== $string) {
    // do it
}

7
投票

这样的事情会起作用:

$string = 'My nAmE is Tom.';
$array = array("name", "tom");
foreach ($array as $token) {
    if (stristr($string, $token) !== FALSE) {
        print "String contains: $token\n";
    }
}

7
投票

我们可以检查给定字符串中是否存在数组的任何元素。

$string = 'My nAmE is Tom.';
$array = array("name","tom");

if(str_replace($array, '', strtolower($string)) !== strtolower($string)) {
   // If String contains an element from array      
   // Do Something
}

1
投票

这能完成工作吗?

$words = explode(" ", $string);
$wordsInArray = array();
foreach($words as $word) {
    if(in_array($word, $array)) {
        $wordsInArray[] = $word;
    }
}

1
投票
<?php

$input = preg_quote('blu', '~'); // don't forget to quote input string!
$data = array('orange', 'blue', 'green', 'red', 'pink', 'brown', 'black');

$result = preg_grep('~' . $input . '~', $data);
print_r($result);

?>

1
投票

这是一个使用 PHP 8+ 函数的可重用辅助函数

str_contains
:

function str_contains_any($haystack, $needles, $case_sensitive)
{
    foreach ($needles as $needle)
    {
        if (str_contains($haystack, $needle) || (($case_sensitive === false) && str_contains(strtolower($haystack), strtolower($needle))))
        {
            return true;
        }
    }
    
    return false;
}

使用示例:

$haystack = 'This is a load of shizzle';
$needles = ['fudge', 'shizzle'];
$match_found = str_contains_any($haystack, $needles, true); //true

1
投票

这是熟悉正则表达式的理想任务,这样您就可以拥有一个健壮、易于适应且直接的脚本。

了解自己的匹配标准很重要。

  1. 您想要不区分大小写的匹配吗?
  2. 您想要整个单词还是部分匹配?
  3. 是否需要支持遇到多字节/unicode字符的可能性?

这里有一组模式,展示了一些可能的组合。请注意,大多数工具是通过结束模式定界符之后的“模式修饰符”完成的。

\b
表示“单词边界”;如果您不熟悉这个元字符,请投入更多研究并在 Stack Overflow 上找到实现它们的其他帖子。

代码:(演示

$string = 'My nAmE ïs Tom.';

// case-sensitive matching, including partial matching
$array = ['foo', 'nAmE'];
$regex[] = '#' . implode('|', array_map('preg_quote', $array)) . '#';

// case-insensitive matching, including partial matching
$array = ['foo', 'om'];
$regex[] = '#' . implode('|', array_map('preg_quote', $array)) . '#i';

// case-insensitive matching, full word matching only
$array = ['foo', 'tom'];
$regex[] = '#\b(?:' . implode('|', array_map('preg_quote', $array)) . ')\b#i';

// case-insensitive matching, full word matching only, multibyte aware
$array = ['foo', 'ïs'];
$regex[] = '#\b(?:' . implode('|', array_map('preg_quote', $array)) . ')\b#iu';


foreach ($regex as $r) {
    if (preg_match($r, $string, $m)) {
        echo "found '$m[0]' using $r on $string\n";
    } else {
        echo "no match using $r on $string\n";
    }
}

通过使用

preg_quote()
的转义字符列表中包含的分隔符(例如
#
),您可以简单地通过
preg_quote
内的名称来调用
array_map()


0
投票
function contains($str, $arr)
{
  $ptn = '';
  foreach ($arr as $s) {
    if ($ptn != '') $ptn .= '|';
    $ptn .= preg_quote($s, '/');
  }
  return preg_match("/$ptn/i", $str);
}

echo contains('My nAmE is Tom', array('name', 'tom'));

0
投票

使用 array_intersect() 函数的另一种方法,请尝试以下代码:

function checkString(array $arr, $str) {

  $str = preg_replace( array('/[^ \w]+/', '/\s+/'), ' ', strtolower($str) ); // Remove Special Characters and extra spaces -or- convert to LowerCase

  $matchedString = array_intersect( explode(' ', $str), $arr);

  if ( count($matchedString) > 0 ) {
    return true;
  }
  return false;
}

0
投票

我做了一些测试,因为我需要根据我们不允许的单词列表检查用户输入。

我发现将所有内容转换为小写(因为我的列表是小写)然后使用数组相交是迄今为止最快的。

    **First Option I Tested**
    $tempString= explode(' ',strtolower($string));
    $foundWords = array_intersect($tempString,$profanities);
    Time taken: 0.00065207481384277 

    **The second option I tested**
    $tempWords = explode(' ',$words);
    foreach ($tempWords as $word)
    {
        foreach ($profanities as $profanity)
        {
            if (stripos($word,$profanity) !== false) return true;
        }
    }
    Time Taken: 0.024131059646606

0
投票

还有更简单的方法

   $string = 'My nAmE is Tom.';
   $convert=explode(" ",$string,5);
   if(in_array("My", $convert)){

      echo "Ja";
   }else{

      echo "Nein";
   }

0
投票
/**
 * ! Only assumes that $needles strings does not contain the character '|'
 */
function contains(string $haystack, array $needles)
{
    $regex = '/' . str_replace('\|', '|', preg_quote(implode('|', $needles))) . '/i';

    return preg_match($regex, $haystack);
}

代码演示:https://3v4l.org/lY6qo#v8.1.4

正则表达式演示:https://www.phpliveregex.com/p/E4s

© www.soinside.com 2019 - 2024. All rights reserved.