I am using the following code:
<?php
$pattern = "/(?<item>.*)\:(?<value>.*)(\{(?<flag>.*)_(?<level>.*)\})/i";
$subject = "item:value{L_300}";
preg_match($pattern, $subject, $matches);
print_r($matches);
Which will output the following:
array(
array (
0 => 'item:value{L_300}',
'item' => 'item',
1 => 'item',
'value' => 'value',
2 => 'value',
3 => '{L_300}',
'flag' => 'L',
4 => 'L',
'level' => '300',
5 => '300'
)
)
My problem is that the subject will not always contain the ‘{L_300}’ part, but I still need to match the ‘item:value’ part using the pattern.
Can any one help?
This may seem like a commonly asked question but I couldn’t find an answer.
You can add a ? after the capturing group to make it optional. I also took the liberty to change some other parts of the pattern to prevent .* capturing too much in unusual cases (such as where there’s an extra : or { character)
Output: