1

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 Answers 2

3
preg_match('/\[(.*?)\]/', $string, $match);
$substring = $match[1];
Sign up to request clarification or add additional context in comments.

4 Comments

@binary: in case there are many such substrings, you'd want to capture them individually I suppose.
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]"
@binary: .*? is a lazy quantifier, the same what 'U' flag does: Matches pattern of any length but prefers the shortest one.
@SilentGhost: didn't know about such usage of ?, tx for explanation
1

Try:

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

var_dump ($substring);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.