Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Regex with parentheses

Tags:

regex

php

I have the below string:

test 13 (8) end 12 (14:48 IN 1ST)

I need the output to be:

14:48 IN 1ST

or everything inside parentheses towards the end of the string.

I don't need, 8 which is inside first set of parentheses. There can be multiple sets of parentheses in the string. I only need to consider everything inside the last set of parentheses of input string.

like image 593
user1058797 Avatar asked May 24 '26 09:05

user1058797


1 Answers

Regex Explanation

.*       Go to last
\(       Stars with (
([^)]*) 0 or more character except )
\)       Ends with 

preg_match

$str = "test 13 (8) end 12 () (14:48 IN 1ST) asd";
$regex = "/.*\(([^)]*)\)/";
preg_match($regex,$str,$matches);

$matches
array (
  0 => 'test 13 (8) end 12 () (14:48 IN 1ST)',
  1 => '14:48 IN 1ST',
)

Accept Empty preg_match_all

$str = "test 13 (8) end 12 () (14:48 IN 1ST) asd";
$regex = "/\(([^)]*)\)/";

preg_match_all($regex,$str,$matches);

$matches
array (
  0 => 
  array (
    0 => '(8)',
    1 => '()',
    2 => '(14:48 IN 1ST)',
  ),
  1 => 
  array (
    0 => '8',
    1 => '',
    2 => '14:48 IN 1ST',
  ),
)

Don't Accept Empty preg_match_all

$str = "test 13 (8) end 12 () (14:48 IN 1ST) asd";
$regex = "/\(([^)]+)\)/";

preg_match_all($regex,$str,$matches);

$matches
array (
  0 => 
  array (
    0 => '(8)',
    1 => '(14:48 IN 1ST)',
  ),
  1 => 
  array (
    0 => '8',
    1 => '14:48 IN 1ST',
  ),
)
like image 102
Utku Yıldırım Avatar answered May 25 '26 22:05

Utku Yıldırım



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!