在PHP中的方括号之间捕获文本 [英] Capturing text between square brackets in PHP

查看:72
本文介绍了在PHP中的方括号之间捕获文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要某种方式来捕获方括号之间的文本.因此,例如,以下字符串:

I need some way of capturing the text between square brackets. So for example, the following string:

[This] is a [test] string, [eat] my [shorts].

可用于创建以下数组:

Array ( 
     [0] => [This] 
     [1] => [test] 
     [2] => [eat] 
     [3] => [shorts] 
)

我有以下正则表达式,/\[.*?\]/,但它仅捕获第一个实例,所以:

I have the following regex, /\[.*?\]/ but it only captures the first instance, so:

Array ( [0] => [This] )

如何获得所需的输出?请注意,方括号是从不嵌套的,因此不必担心.

How can I get the output I need? Note that the square brackets are NEVER nested, so that's not a concern.

推荐答案

匹配所有带括号的字符串:

Matches all strings with brackets:

$text = '[This] is a [test] string, [eat] my [shorts].';
preg_match_all("/\[[^\]]*\]/", $text, $matches);
var_dump($matches[0]);

如果您想要不带括号的字符串:

If You want strings without brackets:

$text = '[This] is a [test] string, [eat] my [shorts].';
preg_match_all("/\[([^\]]*)\]/", $text, $matches);
var_dump($matches[1]);

不带括号的替代版本,匹配速度较慢(使用"*"代替"[^]"):

Alternative, slower version of matching without brackets (using "*" instead of "[^]"):

$text = '[This] is a [test] string, [eat] my [shorts].';
preg_match_all("/\[(.*?)\]/", $text, $matches);
var_dump($matches[1]);

这篇关于在PHP中的方括号之间捕获文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆