Get DDD in (11) with regex

0

I need to get the DDD that is among the Parisians:

(11) 9.9999-9999

I tried to make a regex but I did not succeed. I'll use PHP to get it, but I needed a regex for it. Someone could give me a hand.

    
asked by anonymous 14.06.2018 / 02:18

2 answers

7

You can use the expression ^\((\d{2})\)

Explaining:

  • ^ - Corresponds to the beginning of a string without consuming any characters.
  • \( and \) - Escape is required to be treated as text and not as a set.
  • (\d{2}) - Capture and group the DDD.

See PHP Live Regex

Code

$Telefone = '(11) 9.9999-9999';
preg_match("/^\((\d{2})\)/", $Telefone, $Saida);
print_r($Saida);

Exit

Array
(
    [0] => (11)
    [1] => 11
)

See working at eval.in

    
14.06.2018 / 02:39
5

The response from @NoobSaibot is very good, but I'd like to leave a variation where you get the same result using preg_split with a different Regular Expression.

<?php
$string = "(11) 9.9999-9999";
$ddd = preg_split("/\(|\)/", $string);
echo $ddd[1]; // retorna 11
?>

Explanation of regex:

\( -> abre parênteses
|  -> "ou"
\) -> fecha parênteses

This will break the array string by the two parentheses (opening and closing), resulting in:

Array
(
   [0] => ""
   [1] => "11"
   [2] => " 9.9999-9999"
)

Try Ideone

    
14.06.2018 / 04:26