Search REGEXP in json does not work correctly when used string with parentheses

0

I created a regular expression that does a search in JSON for the name and value of the field, but does not work correctly when the fetched value contains parentheses, like a DDD for example, so in this case the search ignores the parentheses and brings all results that have the searched value anywhere, (11) for example, and not only when this value is in parentheses, being a DDD.

My regular expression:

$Search = sprintf('\'"%s":"([^"]*)%s([^"]*)"\'', 'telefone', '(11)');

Search:

Contatos::whereRaw("contains REGEXP {$Search}")->get();

Values returned:

( 11 ) --954584

(45) --4 11 081

(62) - 53 11 07

Update: In this test I am using preg_match to search a string containing the phone field, realize that instead of the regular expression returning only the DDD, it is returning the number 5 011 in the phone number, ignoring the parentheses.

$DDD = '(011)';
$json = '{"name":"Teste JSON","email":"[email protected]","telefone":"(011) 5011-3344"}';
preg_match(sprintf('\'"telefone":"([^"]*)%s([^"]*)"\'', $DDD), $json, $matches);
var_dump($matches);

Result:

array(4) {
  [0]=>
  string(28) ""telefone":"(011) 5011-3344""
  [1]=>
  string(7) "(011) 5"
  [2]=>
  string(3) "011"
  [3]=>
  string(5) "-3344"
}

What do I need to change in this regular expression so that these parentheses are not ignored?

    
asked by anonymous 14.05.2015 / 09:10

1 answer

1

Your regular expression passes 11 as a group, so that the regular expression captures the parentheses you should escape them with a backslash:

$Search = sprintf('\'"%s":"([^"]*)%s([^"]*)"\'', 'telefone', '\(11\)');

In the second example you use (011) so it would be nice to add an optional "0" with 0? . there are also groups in your expression that are not used ([^"]*) and these parentheses can be removed. Also, your regular expression delimiter ( \' ) can cause confusion, I suggest using / or # . That way it stays:

$Search = sprintf('#"%s":"[^"]*%s[^"]*"#', 'telefone', '\(0?11\)');
    
19.05.2015 / 13:17