There is a line: Сочи (Адлер) (Россия) from which I need to remove the text that is in the last brackets. That is, the text of Россия . For this, I wrote a regular expression:

 preg_match('/\((.*?)\)$/', ...); 

But for some reason it brings me the following matches:

 array(2) { [0]=> string(27) "(Адлер) (Россия)" [1]=> string(25) "Адлер) (Россия" } 

But why? After all, I put at the end of $ , which means the end of the line.

  • .*\((.*?)\)$ - why ... - because you are looking from 1 open bracket to the last open bracket - Alex

3 answers 3

Correct the pattern so that it does NOT look for the parentheses at the end of the line:

 $str = 'Сочи (Адлер) (Россия)'; preg_match('~\(([^()]+)\)$~', $str, $arr); var_dump($arr); 

Result:

 array (size=2) 0 => string '(Россия)' (length=14) 1 => string 'Россия' (length=12) 
  • And if in the line after the last bracket there will be any character or space? - Let's say Pie
  • @ Let'ssayPie is a mess, because it is not for nothing that a vehicle has an anchor $ . But if you need it, you can also add the necessary character class to the template. - Edward
 preg_match('/\(([^)]*)\)[^(]*$/', 'Сочи (Адлер) (Россия)', $match); print_r($match); 

Result:

 Array ( [0] => (Россия) [1] => Россия ) 
     $re = '/(?!.*\()[а-я]+/iu'; $str = 'Сочи (Адлер) (Россия)'; preg_match($re, $str, $matches); var_dump($matches); array(1) { [0]=> string(12) "Россия" } 

    Test