简体   繁体   中英

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].

$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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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