You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PHP正则提取括号内不含text*等前缀的目标内容?

Solution to Extract Target Content from Square Brackets

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 like text, email, textarea)
    • \*?: Matches an optional asterisk (for prefixes like text* or email*)
    • \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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 17:52:26