44

How can i check if a $string contains any of the items expressed in an array?

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

Any ideas?

tarnfeld
  • 24,994
  • 39
  • 109
  • 145

15 Answers15

102

I don't think there is a built-in function that will handle what you want. You could easily write a contains() function however:

function contains($str, array $arr)
{
    foreach($arr as $a) {
        if (stripos($str,$a) !== false) return true;
    }
    return false;
}
zombat
  • 90,260
  • 24
  • 155
  • 163
  • 42
    +1 for not being ridiculously complex, using regexes, or trying to fit it all in one line. – hobodave Jan 24 '10 at 04:55
  • 4
    Why not regexp? I think its not to diffucult to interpret preg_match('/'.implode('|', $arr).'/i', $str) – velop Apr 01 '15 at 08:50
  • Nice and simple @velop :) I wonder which one is more performant. – Jammer Sep 30 '16 at 10:29
  • 1
    @velop While a valid approach, that is not functionally equivalent. The array would need to be written in consideration of being matched via regex. Otherwise if any strings in the array include a / or | or any other modifiers it will provide unexpected results. – Elle H Jan 22 '18 at 20:56
  • 4
    Tip for developers using Laravel: this method exists in the framework from 5.7 onwards as `Str::contains(string $haystack, array|string $needles)` and as `str_contains(string $haystack, array|string $needles)` for version 5.6. https://laravel.com/docs/8.x/helpers#method-str-contains – alexkb May 21 '21 at 05:44
  • 1
    Thanks @alexkb, I'm using L8 and that's what we need <3 – Bơ Loong A Nhứi Feb 28 '22 at 08:43
25

is that what you wanted? i hope that code is compiling :)

$string = 'My nAmE is Tom.';
$array = array("name","tom");
if(0 < count(array_intersect(array_map('strtolower', explode(' ', $string)), $array)))
{
  //do sth
}
TomaszSobczak
  • 2,870
  • 20
  • 24
  • 15
    This would fail on the strings: "Tom, what do you think?" "His 'name' is Tom." among many others. – hobodave Jan 24 '10 at 04:52
16

Using the accepted answer:

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

Just a side note that the if statement could be changed to:

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

since it's not really necessary to use array_map to apply strtolower to each element. instead apply it to the initial string.

kkonstantinov
  • 169
  • 1
  • 3
10

One more workaround for contains function

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

PS. as for me, I'm just use it without function..

if (strlen(str_replace($array, '', $string)) !== strlen($string)) {
    // do it
}
Ivan Ternovtsiy
  • 121
  • 1
  • 7
7

Something like this would work:

$string = 'My nAmE is Tom.';
$array = array("name", "tom");
foreach ($array as $token) {
    if (stristr($string, $token) !== FALSE) {
        print "String contains: $token\n";
    }
}
Paul Osman
  • 4,099
  • 2
  • 25
  • 20
6

We can check if any element of array is exists in a given string.

$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
}
MaYaNk
  • 342
  • 6
  • 13
  • Nice solution. I would prefer [mb_strtolower](https://www.php.net/manual/de/function.mb-strtolower.php) for utf8 characters. – user706420 Nov 18 '21 at 10:16
2
<?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

Will this do the job?

$words = explode(" ", $string);
$wordsInArray = array();
foreach($words as $word) {
    if(in_array($word, $array)) {
        $wordsInArray[] = $word;
    }
}
robertbasic
  • 4,255
  • 1
  • 26
  • 25
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'));
jspcal
  • 49,231
  • 7
  • 69
  • 74
0

Another way to do with array_intersect() function, Try below code :

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;
}
Irshad Khan
  • 5,126
  • 2
  • 42
  • 37
0

I have done some testing because I needed to check user inputs against a list of words we didn't allow.

I have found that converting everything to lowercase (because my list is lowercase) and then using array intersect was by far the fastest.

    **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
Austyn
  • 31
  • 1
0

there is easier Method

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

      echo "Ja";
   }else{

      echo "Nein";
   }
Samee
  • 9
  • 4
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 04 '22 at 22:01
0

Since I have to get the matching count, I used preg_match_all

preg_match_all("/" . implode(' | ', $array) . "/i", " ".str_replace([':', '-'], ' ',$string)." ", $matches);
count($matches[0]);
Sadee
  • 2,574
  • 32
  • 35
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);
}

Code demo: https://3v4l.org/lY6qo#v8.1.4

Regex demo: https://www.phpliveregex.com/p/E4s

medilies
  • 1,343
  • 4
  • 22
-5

Much simpler, please refer the link in_array

$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
echo "Es Irix";
}
CD..
  • 68,981
  • 24
  • 147
  • 156
Alejandro Moreno
  • 5,296
  • 2
  • 30
  • 28