简体   繁体   English

用于获取php中字符串中[]之间内容的正则表达式

[英]regular expression for getting the content between [ ] in string in php

I need to output the strings between [].我需要输出 [] 之间的字符串。 For example I need this-echo, nobody to be displayed.例如我需要这个回声,没有人显示。 But I am get this as result: [this-echo] Hello Everybody [nobody].但我得到的结果是:[this-echo] 大家好 [没人]。

$txt = 'Hello World [this-echo] Hello Everybody [nobody]';
$regExp = '/\[([^)]+)\]/';
$match = preg_match("/\[(.*)\]/s", $txt, $output);

Try this尝试这个

preg_match_all('/\[(.*?)\]/', $txt, $out);
print_r($out[1]);

get得到

Array ( [0] => this-echo [1] => nobody )

Instead of excluding the closing square bracket, you have excluded the closing round bracket in your character class: [^)] That is why the pattern doesn't stop at the first closing square bracket and reach the last of the string.您没有排除结束方括号,而是排除了字符类中的结束圆括号: [^)]这就是为什么模式不会在第一个结束方括号处停止并到达字符串的最后一个的原因。

You only need to replace it with [^]] and to use preg_match_all to get several results.你只需要用[^]]替换它并使用preg_match_all来获得几个结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM