How do I match a square bracket literal using RegEx?


Question

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

1
17
11/14/2011 11:41:29 AM

Accepted Answer

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

28
12/28/2017 4:55:24 AM

Works flawlessly:

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

Output:

abecd

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon