What's the regex to match a square bracket? I'm using \\]
in a pattern in eregi_replace
, but it doesn't seem to be able to find a ]
...
You can omit the first backslash. [[\]] will match either bracket. In some regex dialects (e.g. grep) you can omit the backslash before the ] if you place it immediately after the [ (because an empty character class would never be useful): [][] .
The [] construct in a regex is essentially shorthand for an | on all of the contents. For example [abc] matches a, b or c. Additionally the - character has special meaning inside of a [] . It provides a range construct. The regex [a-z] will match any letter a through z.
The way we solve this problem—i.e., the way we match a literal open parenthesis '(' or close parenthesis ')' using a regular expression—is to put backslash-open parenthesis '\(' or backslash-close parenthesis '\)' in the RE. This is another example of an escape sequence.
\]
is correct, but note that PHP itself ALSO has \
as an escape character, so you might have to use \\[
(or a different kind of string literal).
Works flawlessly:
<?php $hay = "ab]cd"; echo eregi_replace("\]", "e", $hay); ?>
Output:
abecd
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With