I'm using preg_match with PHP 5.6 to retrieve a value from a string. (I'm newb with preg_match)
It goes with this format:
data[SearchForm][somestringhere]
And I need to be able to retrieve the 'somestringhere' value.
I tried doing it this way:
$search_field_pattern = "/\bdata[SearchForm][[a-zA-Z]]\b/i";
if(preg_match($search_field_pattern, "foo")) {
debug('foobar!');
}
But it's not working. Can someone give me a hint why it's not working and what I should do to correctly approach this solution?
Thank you.
You may use
$search_field_pattern = "/\bdata\[SearchForm]\[(\w+)]/i";
if(preg_match($search_field_pattern, "data[SearchForm][somestringhere]", $m)) {
echo $m[1]; // => somestringhere
}
See the PHP demo
The pattern matches
\b
- a word boundarydata\[SearchForm]\[
- a literal string data[SearchForm][
(note [
are escaped to match literal [
chars)(\w+)
- capturing group 1: one or more word chars]
- a ]
char.The third argument to preg_match
, $m
, will hold the results. Since the necessary substring is captured into Group 1, the value is retrieved using $m[1]
.
if(preg_match("~\[(\w+)](?!.*\[\w+])~s", "data[SearchForm][somestringhere]", $m)) {
echo $m[1]; // => somestringhere
}
See this PHP demo.
To get the second one, use
if(preg_match("~\[\w+].*?\[(\w+)]~s", "data[SearchForm][somestringhere]", $m)) {
echo $m[1]; // => somestringhere
}
See yet another PHP demo.