Reputation: 26556
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?
Upvotes: 55
Views: 85272
Reputation: 47900
This is an ideal task to familiarize yourself with regular expressions so that you have a robust, easily adaptable, and direct script.
It is important to understand your own criteria for matching.
Here is a battery of patterns that demonstrate a few likely combinations. Notice that most of the tooling is done via "pattern modifiers" after the closing pattern delimiter. The \b
means a "word boundary"; if you are not familiar with this metacharacter, please invest in more research and find other posts on Stack Overflow that implement them.
Code: (Demo)
$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";
}
}
By using a delimiter which is included in preg_quote()
's list of escaped characters (e.g. #
), you can simply call preg_quote
by its name inside of array_map()
.
Upvotes: 1
Reputation: 119
One more workaround for contains function
function contains($string, $array, $caseSensitive = true)
{
$strippedString = $caseSensitive ? str_replace($array, '', $string) : str_ireplace($array, '', $string);
return $strippedString !== $string;
}
PS. as for me, I'm just using it without function...
if (str_replace($array, '', $string) !== $string) {
// do it
}
Upvotes: 9
Reputation: 8299
Here's a reusable helper function that uses the PHP 8+ function 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;
}
Usage example:
$haystack = 'This is a load of shizzle';
$needles = ['fudge', 'shizzle'];
$match_found = str_contains_any($haystack, $needles, true); //true
Upvotes: 2
Reputation: 2218
/**
* ! 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
Upvotes: 0
Reputation: 67
there is easier Method
$string = 'My nAmE is Tom.';
$convert=explode(" ",$string,5);
if(in_array("My", $convert)){
echo "Ja";
}else{
echo "Nein";
}
Upvotes: 0
Reputation: 51
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
Upvotes: 0
Reputation: 429
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
}
Upvotes: 8
Reputation: 6046
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;
}
Upvotes: 0
Reputation: 331
<?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);
?>
Upvotes: 1
Reputation: 187
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.
Upvotes: 17
Reputation: 51904
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'));
Upvotes: 0
Reputation: 4117
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";
}
}
Upvotes: 6
Reputation: 94167
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;
}
Upvotes: 112
Reputation: 2926
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
}
Upvotes: 25
Reputation: 4335
Will this do the job?
$words = explode(" ", $string);
$wordsInArray = array();
foreach($words as $word) {
if(in_array($word, $array)) {
$wordsInArray[] = $word;
}
}
Upvotes: 1