I have a string from which I need to capture one and possibly two substrings (using PHP):
- The first one is mandatory
- The second one is optional
- The first and second ones are separated by unknown junk
- The second one may or may not be followed by more junk I don't care about
I am unable to make my pattern capture the second pattern unless I make it mandatory in the pattern string. This makes the pattern fail when only the first pattern is available in the subject.
I'm stumped. This shouldn't be that hard.
<?php
// sometimes the subject looks like this:
//$subject = 'pattern 111 -then some random junk-';
$subject = 'pattern 111 -then some random junk- pattern 222';
preg_match('/(pattern 111)(.*?)(pattern 222)?/', $subject, $matches);
print_r($matches);
?>
This is what I get from the above:
Array
(
[0] => pattern 111
[1] => pattern 111
[2] =>
)
Seems to boil down to how do I make {0,1} (that is, the final ? operator in the pattern) be more greedy (ironic given that as a quantifier modifier it does the opposite)