tags:

views:

2623

answers:

6

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 ]...

+4  A: 

Works flawlessly:

<?php
    $hay = "ab]cd";
    echo eregi_replace("\]", "e", $hay);
?>

Output:

abecd
Bombe
+3  A: 

\] 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).

Michael Borgwardt
A: 

You problem may come from the fact you are using eregi_replace with the first parameter enclosed in simple quotes:

 '\['

In double quotes, though, it could works well depending on the context, since it changes the way the parameter is passed to the function (simple quotes just pass the string without any interpretation, hence the need to double to "\" character).

Here, if "\[" is interpreted as an escape character, you still need to double "\".

Note: based on your comment, you may try the regex

<\s*(?:br|p)\s*\/?\s*\>\s*\[

in order to detect a [ right after a <br>or a <p>

VonC
I don't follow you... I _am_ using double quotes in my code and it isn't working.
aalaap
I would have say the reverse, in single quotes, backslash is a character like the others, except before backslash and single quote, IIRC.
PhiLho
Just tried Bombe's code, works fine with '\]', '\\]', "\]" and "\\]"... Actually, ] doesn't need to be escaped if there is no [ before it.
PhiLho
A: 

In .Net you escape special characters by adding up a backslash; "\" meaning it would become; "["...

Though since you normally do this in string literals you would either have to do something like this;

@"\["

or something like this;

"\\["
Thomas Hansen
I'm using PHP, so I'm not sure this would be of any help to me...
aalaap
Sorry, then I can't help you :( Though the RegEx syntax should mostly be kind of similar...
Thomas Hansen
+1  A: 

You don't need to escape it: if isolated, a ] is treated as a regular character.
Tested with eregi_replace and preg_replace.

[ is another beast, you have to escape it. Looks like single and double quotes, single or double escape are all treated the same by PHP, for both regex families.

Perhaps your problem is elsewhere in your expression, you should give it in full.

PhiLho
A: 

There are two ways of doing this:

/ [\]] /x;

/  \]  /x;

While you may consider the latter as the better option, and indeed I would consider using it in simpler regexps. I would consider the former, the better option for larger regexps. Consider the following:

/ (\w*) (  [\d\]] ) /x;

/ (\w*) ( \d | \] ) /x;

In this example, the former is my preferred solution. It does a better job of combining the separate entities, which may each match at the given location. It may also have some speed benefits, depending on implementation.

Note: This is in Perl syntax, partly to ensure proper highlighting.
In PHP you may need to double up on the back-slashes. "[\\]]" and "\\]"

Brad Gilbert