How to extract text in parentheses with regex in php

Asked

Viewed 2,067 times

5

I have the text:

Regular expressions (often abbreviated to "regex") are a declarative language used for correspondence.

How do I get the content included in the parentheses?

I tried to:

$texto = "As expressões regulares (muitas vezes abreviado para "regex") são uma linguagem declarativa utilizada para correspondência." ;
preg_match("/\(*\)/", $texto, $testando);
var_dump($testando) ;

The exit is:

array (size=1)
   0 => string ')' (length=1)

1 answer

6


Failed to specify which character either house in its regex, in case the point .. In other words, you’ll get a parenthesis followed by anything .* followed by a closure of parenthesis.

$texto = "As expressões regulares (muitas vezes abreviado para 'regex') são uma linguagem declarativa utilizada para correspondência." ;
preg_match("/\(.*\)/", $texto, $testando);
var_dump($testando) ;

Or to pick up the content within the two parentheses, use the function preg_match_all(), change regex to match letters and numbers (\w), characters like space, tab and others (\s) quote (')

$texto = "As expressões regulares (muitas vezes abreviado para 'regex') são uma linguagem (declarativa utilizada) para correspondência";
preg_match_all("#\([\w\s']+\)#i", $texto, $testando);
var_dump($testando) ;
  • In the case of: $text = "Regular expressions (often abbreviated to 'regex') are a (declarative) language used for matching." Could bring the 2 sections between parentheses separately?

  • @Taisbevalle, thank you! It worked fine. (often abbreviated to 'regex')

  • It remains to solve the problem cited by @Givanildor.deOliveira. When there are two sequences "654321(GGG) blá (HSH)123456" the return is "(GGG) BLÁ (HSH)" while the desirable would be "(GGG)" and "(HSH)"

  • @Givanildor.deOliveira edited the answer.

  • Fantastic @rray.

Browser other questions tagged

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