Reputation: 397
i want to use preg_match to find text between [{}] for example: $varx = "[{xx}]";
final output will be $match = 'xx';
another example $varx = "bla bla [{yy}] bla bla";
final output will be something like this $match = 'yy';
in other words it strips out bracket. i'm still confusing with regular expression but found that sometimes preg match is more simple solution. searching other example but not meet my need.
Upvotes: 1
Views: 1571
Reputation: 72226
Both kinds of brackets are meta-characters in regex
. If you want to match them you have to escape them (escaping the opening brackets is enough):
$varx = "bla bla [{yy}] bla bla";
preg_match('/\[\{([^\]}]*)}]/', $varx, $matches);
print_r($matches);
It displays:
Array
(
[0] => [{yy}]
[1] => yy
)
The regex
:
/ # delimiter; it is not part of the regex but separates it
# from the modifiers (no modifiers are used in this example);
\[ # escaped '[' to match literal '[' and not use its special meaning
\{ # escaped '{' to match literal '{' and not use its special meaning
( # start of a group (special meaning of '(' when not escaped)
[^ # character class, excluding (special meaning of '[' when not escaped)
\] # escaped ']' to match literal ']' (otherwise it means end of class)
} # literal '}'
] # end of the character class
* # repeat the previous expression zero or more times
) # end of group
}] # literal '}' followed by ']'
/ # delimiter
How it works:
It matches the sequence of [{
characters (\[\{
) followed by zero or more (*
) characters that are not (^
) in the class ([...]
), followed by }]
. The class contains two characters (]
and }
) and everything between [{
and }]
is enclosed in a capturing group ((...)
).
preg_match()
puts in $matches
at index 0
the part of the string that matches the entire regex
([{yy}]
) and on numeric indices starting with 1
the substrings that match each capturing group.
If the input string contains more than one [{...}]
block you want to match then you have to use preg_match_all()
:
preg_match_all('/\[\{([^\]}]*)}]/', $varx, $matches, PREG_SET_ORDER);
When the fourth argument is PREG_SET_ORDER
, $matches
contains a list of arrays as exposed above.
Upvotes: 1
Reputation: 3389
This one should work for you:
preg_match('/\[\{([^\]\}]+)\}\]/', $varx, $match);
Upvotes: 2