在 PHP 中捕获方括号之间的文本 [英] Capturing text between square brackets in PHP
本文介绍了在 PHP 中捕获方括号之间的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要某种方法来捕获方括号之间的文本.例如,以下字符串:
I need some way of capturing the text between square brackets. So for example, the following string:
【这个】是一个【测试】字符串,【吃】我的【短裤】.
可用于创建以下数组:
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屋!
查看全文