Reputation: 805
My situation is: I'm processing an array word by word. What I'm hoping to do and working on, is to capture a certain word. But for that I need to test two patterns or more with preg-match.
This is my code :
function search_array($array)
{
$pattern = '[A-Z]{1,3}[0-9]{1,3}[A-Z]{1,2}[0-9]{1,2}[A-Z]?';
$pattern2 = '[A-Z]{1,7}[0-9]{1,2}';
$patterns = array($pattern, $pattern2);
$regex = '/(' .implode('|', $patterns) .')/i';
foreach ($array as $str) {
if (preg_match ($regex, $str, $m)){
$matches[] = $m[1];
return $matches[0];
}
}
}
Example of array I could have :
Array ( [0] => X [1] => XXXXXXX [2] => XXX [3] => XXXX [4] => ABC01DC4 )
Array ( [0] => X [1] => XXXXXXX [2] => XXX [3] => ABCDEF4 [4] => XXXX [5] => XX )
Words I would like to catch :
-In the first array : ABC01DC4
-In the second array : ABCDEF4
The problem is not the pattern itself, it's the syntax to use multiple pattern in the same pregmatch
Upvotes: 1
Views: 7304
Reputation: 39355
Your code worked with me, and I didn't find any problem with the code or the REGEX. Furthermore, the description you provided is not enough to understand your needs.
However, I have guessed one problem after observing your code, which is, you didn't use any anchor(^...$
) to perform matching the whole string. Your regex can find match for these inputs: %ABC01DC4V
or ABCDEF4EE
. So change this line with your code:
$regex = '/^(' .implode('|', $patterns) .')$/i';
-+- -+-
Upvotes: 4