Get content that is enclosed in parentheses using regex

3

I've been studying regex a lot, but I got caught trying to "clean" a text, leaving only the first occurrence, and the data in parentheses, the string is like this :

$string = "Mais de - valor: R$3.21 - Tipo: (+05)";

As all text before valor , has - separating them, I used explode :

$string2 = explode("-", $string);

I then get, Mais de , I wanted to add (+05) to this result, but in the codes I've tried with preg_match only returns (05) without + , remembering that this symbol of more can also be a symbol of less than - , type (-05) , does anyone know how to delimit quotes in regex ? I want the end result to be something like:

  

More than (+05)

Instead of% original%.

For those who help me, please comment on your code for me to try to understand.

    
asked by anonymous 20.05.2015 / 08:51

3 answers

2

You can use only a regex for this: /^([^-]+)[^\(]+(\([^\)]+\))/

In this case you do not need the explode and you can only use:

$string = "Mais de - valor: R$3.21 - Tipo: (+05)";
preg_match('/^([^-]+)[^\(]+(\([^\)]+\))/', $string, $match);
echo $match[1].$match[2];

Example: link

The regex I used has 2 capture groups. At first, [^-]+ accepts n characters that are not - to limit to the - you are currently using to explode it. In the second, \([^\)]+\) , it looks for parentheses that have to be escaped and accepts n characters that are not ) , i.e. until you find the parenthesis lock.

    
20.05.2015 / 09:56
2

You can do this without using regex :

$texto = "Mais de - valor: R$3.21 - Tipo: (+05)";

$parte1 = strstr($texto, "-", true);     // Retorna a 1ª ocorrência antes de "-"

$inicio = strpos($texto, "(");           // Encontra a posição da 1ª ocorrência do "("
$fim = strpos($texto, ")", $inicio) + 1; // Encontra a posição da 1ª ocorrência de ")" após "("

$parte2 = substr($texto, $inicio, $fim - $inicio);

echo $parte1 . $parte2 . "\n";           // Mais de (+05)

View demonstração

Use regular expressions only if you really need them.

    
20.05.2015 / 09:29
2

If (+05) is always fixed, you can use the last 5 characters.

$str = 'Mais de - valor: R$3.21 - Tipo: (+05)';
echo strstr( $str , ' - ' , true ) . ' ' . substr( $str , -5 );

Output : More than (+05)

Demo

    
20.05.2015 / 10:01