如何用PHP正则提取括号内不含text*等前缀的目标内容?
Got it, let's break down how to adjust your regex to get exactly what you need.
Your original regex \[([^]]+)] grabs everything inside the square brackets, but we need to tweak it to ignore those prefixes like text*, email*, or textarea and only keep the identifier part after them.
The Updated Regex
Use this pattern:
\[(?:\w+\*?\s+)?([^\]]+)]
How It Works
Let's break down each part clearly:
\[: Matches the opening square bracket (escaped because[is a special regex character)(?:\w+\*?\s+)?: This is a non-capturing group (the?:means we don't save this part) that handles optional prefixes:\w+: Matches one or more word characters (covers prefixes liketext,email,textarea)\*?: Matches an optional asterisk (for prefixes liketext*oremail*)\s+: Matches one or more spaces separating the prefix from your target content?: Makes the entire prefix group optional, so it works for cases like[area-without-attribute]where there's no prefix at all
([^\]]+): This is the capturing group we care about—it matches all characters except the closing square bracket, which is exactly the identifier you want to keep\]: Matches the closing square bracket
How to Use It
When you run this regex against your input string, extract all matches from the first capturing group. For your sample input:
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
You'll get the exact output you're looking for:
your-test your-tester your-testerer your-testererer area-without-attribute
Quick Adjustment Note
If your prefixes ever include characters like hyphens (e.g., [custom-field* your-id]), you can update the \w+ to [\w-]+ to cover those edge cases.
内容的提问来源于stack exchange,提问作者Some Name

