1

I am having trouble extracting some patterns from a string using PHP. Here is the example string:

"New [[supplier]] price request for [[legal-entity]]"

What I need to do is extract all the "merge tags" (in brackets), from that string and output in an array. The array I need is:

array(
    0 => "[[supplier]]',
    1 => "[[legal-entity]]"
);
2

1 Answer 1

1

You can use the expression:

\[\[[^]]+\]\]
  • \[\[ Two [ brackets.
  • [^]]+ Negated character set, anything that is not a ].
  • \]\] Two ] brackets.

Regex demo here.


In PHP:

<?php

$input = 'New [[supplier]] price request for [[legal-entity]]';

$matches = array();
preg_match_all('/\[\[[^]]+\]\]/s', $input, $matches);
print_r($matches);

Prints:

[0] => Array
        (
            [0] => [[supplier]]
            [1] => [[legal-entity]]
        )

PHP demo here.

Sign up to request clarification or add additional context in comments.

2 Comments

I like that character negation, nice one
You are welcome. Cheers @DarraghEnright, yes the negated character set requires less steps than matching anything lazily, compare the two debuggers: negated character set vs anything lazily

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.