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
Set up your input string:
$stringText = 'Example text [1212sdas|4542189789/] continue text...';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)
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
相关产品推荐
相关产品推荐

