I'm using the following regex to match the string below, so far so good. Now, how could I make the content of BAZ
optional so it matches cases where BAZ ()
?
$str = '- 10 TEST (FOO 3 TEST.BAR 213 BAZ (\HELLO) TEST';
preg_match('/FOO (\d+).+BAR (\d+).+BAZ \(\\\\(\w+)\)/i', $str, $match);
$str = '- 10 TEST (FOO 3 TEST.BAR 213 BAZ () TEST';
$array = array(
'FOO' => 3,
'BAR' => 213,
'BAZ' =>
);
Sounds like you just want to wrap the whole thing in a non-capturing group and add a ?
operator.
/FOO (\d+).+BAR (\d+).+BAZ (?:\(\\\\(\w+)\))?/i
Note that this captures BAZ with no parentheses after it. If you're looking for BAZ () instead, use this:
/FOO (\d+).+BAR (\d+).+BAZ \((?:\\\\(\w+))?\)/i