Skip to content
Advertisement

PHP preg_match_all – extract content from pattern in different order

I’m cleaning up some wordpress short codes in my code and I’m looking for a solution that would extract the right values no matter the order of the values.

Example:

JavaScript

If I want to extract my_label, my_url and other_value, I would use the following structure:

JavaScript

The problem is that I sometimes have a different order like this:

JavaScript

My previous preg_match_all doesn’t work with this. I have tried to put each pattern between (…) or use | but I don’t get the expected result. I have seen solutions here to identify strings but I need more than identifying strings, I need to extract values.

It’s probably something trivial for a regex expert.

Thanks

Advertisement

Answer

If the properties could also be a different amount in any order and should start with [Links , you can make use of the G anchor. The key is in capture group 1, the value in capture group 2.

JavaScript

Explanation

  • (?: Non capture group
    • [Links Match [Links
    • | Or
    • G(?!^) Assert the position at the end of the previous match, not at the start
  • ) Close non capture group
  • (?=[^][]*]) Positive lookahead, assert a ] at the right
  • h+ Match 1+ horizontal whitespace chars
  • ( Capture group 1
    • [^s=]+ Match 1+ times any char except = or a whitespace char
  • ) Close group 1
  • =" Match literally
  • ( Capture group 2
    • [^s"]+ Match 1+ times any char except " or a whitespace char
  • )" Close group 2 and match "

Regex demo

Example

JavaScript

Output

JavaScript

Php demo

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement