I need to extract two seperate in开发者_运维百科formation 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?
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
One way:
list($datatype, $varlength) = explode('(', trim($string, ')'));
This only works if there can be only one opening bracket.
Reference: list
, explode
, trim
.
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);
精彩评论