Search code examples
phppreg-match

preg_match function doesn't work with parenthesis


I'm trying to match an array that contains:

[title] => Something (12) Pieces

with an $item string that contains also Something (12) Pieces with this function:

function in_array_r($item , $array){
    return preg_match('/"'. $item .'"/i' , json_encode($array));
}

But it doesn't give me a match even though they're identical. What am I doing wrong?


Solution

  • What you have to do is escape characters which are special for RegEx. To achieve this you can use the function preg_quote, but be aware that delimiters don't get escaped by preg_quote, if you don't pass the used delimiter (in your case /) to the second argument.

    function in_array_r($item , $array){
        return preg_match('/"'. preg_quote($item, '/') .'"/i' , json_encode($array));
    }
    

    http://php.net/preg_quote https://3v4l.org/p9n43