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

PHP如何匹配并提取以[开头、/]结尾的子串内部内容

Extract Text Between [ and /] in PHP

To pull out the content between [ and /] from your string and get it into an array, the most straightforward approach is using PHP's preg_match_all() function with a tailored regular expression. Here's how to implement it:

Step-by-Step Solution

  1. Set up your input string:

    $stringText = 'Example text [1212sdas|4542189789/] continue text...';
    
  2. Use a regex pattern to target the desired content:
    The pattern /\[([^\]]*?)\// is designed specifically for this case:

    • \[ matches the opening square bracket (escaped because [ is a special regex character)
    • ([^\]]*?) captures any characters except a closing square bracket (the *? makes it non-greedy, so it stops at the first matching / instead of overshooting)
    • \/ matches the forward slash right before the closing bracket (escaped since / acts as the regex delimiter)
  3. Run the match and extract the result array:

    preg_match_all('/\[([^\]]*?)\//', $stringText, $matches);
    $resultArray = $matches[1]; // The captured content lives in the first group of matches
    

Example Output

If you run print_r($resultArray), you’ll get exactly what you need:

Array
(
    [0] => 1212sdas|4542189789
)

Bonus Notes

  • If your string has multiple instances of [.../], this code will automatically capture all of them into the array.
  • The non-greedy quantifier ensures we don’t accidentally match from the first [ to the last /] when multiple occurrences exist.

内容的提问来源于stack exchange,提问作者Rafael Furtado

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 18:04:05