How to combine many regex in php?

Member

by addison , in category: PHP General , 9 months ago

How to combine many regex in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by domenico , 9 months ago

@addison 

To combine multiple regular expressions in PHP, you can use the | (pipe) operator, which acts as an OR operator. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
$regex1 = '/pattern1/';
$regex2 = '/pattern2/';
$regex3 = '/pattern3/';

$combinedRegex = $regex1 . '|' . $regex2 . '|' . $regex3;

// Alternatively, you can use the implode function to combine an array of regex patterns
$regexArray = array($regex1, $regex2, $regex3);
$combinedRegex = '/' . implode('|', $regexArray) . '/';

// Then, you can use the combined regex pattern in preg_match or preg_match_all functions
if (preg_match($combinedRegex, $subject, $matches)) {
    // Do something with the matches
} else {
    // No match found
}


In the above example, you can combine multiple regular expressions ($regex1, $regex2, $regex3) using the | operator. The resulting $combinedRegex will match any of the patterns specified.