1

https://regex101.com/r/xTu3Zo/1/

I have the following regex:

\[([^]]+)]

And the following string:

Je naam (verplicht) [text* your-test] Je e-mailadres (verplicht) [email* your-tester] Onderwerp [text your-testerer] Je bericht [textarea your-testererer] [area-without-attribute] 1

I want to extract everything inbetween the brackets (for example "your-test") without "text*".

Desired output:

your-test 
your-tester 
your-testerer 
your-testererer 
area-without-attribute

How can I achieve this? Thanks!

0

1 Answer 1

3

You may use

\[(?:\w+\*?\s+)?([^][]+)]

See the regex demo. Details:

  • \[ - a [ char
  • (?:\w+\*?\s+)? - an optional sequence of:
    • \w+ - 1+ word chars
    • \*? - an optional asterisk
    • \s+ - 1+ whitespaces
  • ([^][]+) - Group 1: any 1 or more chars other than [ and ]
  • ] - a ] char.

See the PHP demo:

$text = "Je naam (verplicht) [text* your-test] Je e-mailadres (verplicht) [email* your-tester] Onderwerp [text your-testerer] Je bericht [textarea your-testererer] [area-without-attribute]";
if (preg_match_all('~\[(?:\w+\*?\s+)?([^][]+)]~', $text, $matches)) {
    print_r($matches[1]);
}

Output:

Array
(
    [0] => your-test
    [1] => your-tester
    [2] => your-testerer
    [3] => your-testererer
    [4] => area-without-attribute
)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.