开发者

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

开发者 https://www.devze.com 2023-02-19 15:56 出处:网络
I need to extract two seperate in开发者_运维百科formation from a string. For example, $string = \'int(5)\';

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

精彩评论

暂无评论...
验证码 换一张
取 消