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);