In this article, we will explain how to check if a string contains any of array.
We can write it in one line.
Table of Contents
Goal of this article
For examole, we’ll provide PHP code to check if the string “I like bananas.” contains any of the values from the array [‘apple’, ‘banana’, ‘grape’].
Code
Using the implode function, concatenate the array with a pipe character ( | ), and perform an OR search with a regular expression.
This is the simplest method as far as I know.
$fruits = ['apple', 'banana', 'grape'];
$string = 'I like banana';
if(preg_match('{'.implode('|', $fruits).'}i', $string)){
echo "The string contains any from array";
}
That is all, it was about how to check if a string contains any of array using PHP.