Casso
Casso

Reputation: 139

PHP preg_match_all with optional argument

this regex problem exceeds my understanding of complex search patterns: pattern:

<!--TAG\((\d+),([^0-9\)]\w*)\)-->

search text:

<!--TAG(204700,CS)-->
<!--TAG(204700,EN)-->
<!--TAG(204700,CS,def)-->
<!--TAG(204700,EN,rel)-->

The pattern finds me the first two links and puts the ID and language abbreviation into the return array. Now I need to adjust the pattern, so it would find also the third and fourth line a put the third optional argument into the return array. That is beyond me. Thanks for your help.

https://www.phpliveregex.com/p/qeu

Upvotes: 0

Views: 46

Answers (1)

The fourth bird
The fourth bird

Reputation: 163257

You could add an optional part (?:,(\w+))? the matches a comma and captures in a group 1+ word characters:

<!--TAG\((\d+),([^0-9\)]\w*)(?:,(\w+))?\)-->

Regex demo

https://www.phpliveregex.com/p/qev

This part [^0-9\)]\w* is a negated character class which matches not a digit or a ) which for example also matches %

Depending on your requirements, you might change that to [A-Z] or \w+

Upvotes: 1

Related Questions