March 24, 2011

Regex Query To seperate and extract two different set from a string?

Question by mrN

I need to extract two seperate information from a string.

For example,

$string = 'int(5)';
//Now I need "int" and the text inside the brackets "5" seperately;
$datatype = ?
$varlength = ?

How to extract those information?

Answer by Czechnology

Use this regex

^([a-z]+)(([0-9]+))$

if (preg_match('~^([a-z]+)(([0-9]+))$~i', 'int(5)', $matches)) {
  $datatype  = $matches[1]; // int
  $varlength = $matches[2]; // 5
}

EDIT

If you want to match more than just a number in the brackets, expand it as necessary:

^([a-z]+)(([0-9a-zA-Z, ]+))$ // numbers, letters, comma or space
^([a-z]+)(([^)]+))$          // anything but a closing bracket

Answer by Starx

In the case. you want to match anything inside the brackets, use this

preg_match('/^([a-z]+)(([a-zA-Z0-9,]+))$/', 'enum(1,a)' , $matches);
print_r($matches);

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!