Dzhuneyt
Dzhuneyt

Reputation: 8701

Can not match multiple "attributes" in "[shortcode attr=value attr=value]" string with REGEX in PHP

I have the following string:

[jeans size="L"] [jeans color="blue" size="XL"]

And the following regex which I run through PHP's preg_match_all():

#\[(?P<tag_name>\w+)(?:\s*(?P<attr>\w+)\s?[=,:]\s?["\'](?P<value>\w*)["\'])*\s*]#igs

I've tried many variations of the regex and can't seem to get the multiple attributes of a given shortcode, e.g. the color and the size in the second one. Only the last attribute is retrieved per tag.

Here is a fiddle: https://regex101.com/r/hF1tS1/5

enter image description here

Upvotes: 1

Views: 113

Answers (1)

vks
vks

Reputation: 67968

\[(?P<tag_name>\w+)\K|\G(?!^)(?:\s*(?P<attr>\w+)\s?[=,:]\s?["\'](?P<value>\w*)["\'])

You can make use of \G assert position at the end of the previous match or the start of the string for the first match here.See demo.

https://regex101.com/r/yG7zB9/33

Upvotes: 1

Related Questions