I want to search multiple character strings from a certain character string-I tried using preg_match

Aug 26, 2020 PHP Beginner Learning

#I want to search for multiple characters in a string

At first, I was searching for only one character string using strstr, but I want to be able to search for multiple character strings on the way, so think about it. . .

As a result of my worries, I thought about a solution, so make a note.

I used strpos and strstr, but I can only search for one character string. . . I did trial and error what to do if you want to search multiple strings.

I tried using preg_match. preg_match matches by regular expression. If the target string has the string you want to search (matches), 1 is returned. If there is no search string, 0 is returned.

// put multiple strings you want to search in a variable
$search1 ='/red|yellow|blue/';
$search2 ='/black|white/';

// string to search
$val ='red green yellow black peach orange';

if(preg_match($search1, $val) === 1){
 print('includes red, yellow or blue');
}else if(preg_match($search2, $val) === 1){
 print('include black or white');
 print('does not include specified color');

The point is how to write the variable part. Enclose with / and use OR with |.

As mentioned above, by using preg_match, it was possible to perform a string search with multiple conditions.