user1094128
user1094128

Reputation: 461

PHP preg_match match something or nothing and output assoc array

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.

Upvotes: 1

Views: 1017

Answers (1)

Highly Irregular
Highly Irregular

Reputation: 40619

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)

<?php
$pattern = "/(?<item>[^:]*):(?<value>[^{]*)(\{(?<flag>[^_]*)_(?<level>[^}]*)\})?/i";

$subjects = array("itemname:valuehere{L_300}",
"item2:anothervalue"
);

foreach ($subjects as $subject) {
  print "Subject:\n$subject\n";
  preg_match($pattern, $subject, $matches);
  print_r($matches);
}

Output:

Subject:
itemname:valuehere{L_300}
Array
(
    [0] => itemname:valuehere{L_300}
    [item] => itemname
    [1] => itemname
    [value] => valuehere
    [2] => valuehere
    [3] => {L_300}
    [flag] => L
    [4] => L
    [level] => 300
    [5] => 300
)
Subject:
item2:anothervalue
Array
(
    [0] => item2:anothervalue
    [item] => item2
    [1] => item2
    [value] => anothervalue
    [2] => anothervalue
)

Upvotes: 1

Related Questions