Catch DDD nos (11) with regex

Asked

Viewed 910 times

0

I need to get the DDD that’s between the paretenses:

(11) 9.9999-9999

I tried to make a regex but I was not successful. I will use PHP to get it, but I needed a regex for it. Could someone give me a hand.

  • 1

    That ^\((\d{2})\) help ? https://regex101.com/r/aYYEtd/2

2 answers

7


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

Explaining:

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

See in 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 in Eval in.

5

The response of @Noobsaibot is very good, but I would 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 the regex:

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

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

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

Testing at Ideone

  • 1

    I didn’t know this function of PHP.

  • show of rs...

  • It would explode using regex.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.