views:

67

answers:

2

Hi, I have a string in PHP for example $string = "Blabla [word]";

I would like to filter the word between the '[' brackets. The result should be like this $substring = "word";

thanks

+2  A: 
preg_match('/\[(.*?)\]/', $string, $match);
$substring = $match[1];
SilentGhost
perfect, thank you!
Tom Dalenberg
`.*?` or rather just `.*`?
binaryLV
@binary: in case there are many such substrings, you'd want to capture them individually I suppose.
SilentGhost
If there are many such substrings, I would use `preg_match_all()` with 'U' modifier (PCRE_UNGREEDY) instead of `preg_match()`. I can't get though, why do ".*?" and ".*" return different results with strings like "foo [bar] something [else]"
binaryLV
@binary: `.*?` is a lazy quantifier, the same what `'U'` flag does: Matches pattern of any length but prefers the shortest one.
SilentGhost
@SilentGhost: didn't know about such usage of `?`, tx for explanation
binaryLV
+1  A: 

Try:

preg_match ('/\[(.*)\]$/', $string, $matches);
$substring = $matches[1];

var_dump ($substring);
Piotr Pankowski