Search code examples
phpregexescapingstring-literalsparentheses

How to match literal parentheses in a string


I have attempted a preg_match and the result should display hello, which doesn't happen.

$action3 = "(414)-4204";
if (preg_match('%^(\d{3})+-\d{4}$%',$action3)) {
    echo "hello";
} else {
    echo "goodbye";
}

Where did I go wrong?


Solution

  • You need to escape the parentheses with backslashes. They are special characters in Regex.

    preg_match('%^\(\d{3}\)+-\d{4}$%',$action3)