使用preg_match提取模式

时间:2016-09-29 06:31:49

标签: php preg-match

我有一个字符串变量,想要单独提取年份和数字。

$val = '2015(15)';
preg_match ('/(.*?)\((.*?)\)/',$val,$match);
print_r($match);

输出:Array ( [0] => 2015(15) [1] => 2015 [2] => 15 )

预计:以上都可以。或Array ( [0] => 2015 [1] => 15 )

$val = '2015';
preg_match ('/(.*?)\((.*?)\)/',$val,$match);
print_r($match);

输出:Array ( )

预期:Array ( [0] => 2015 [1] => )

$val = '(15)';
preg_match ('/(.*?)\((.*?)\)/',$val,$match);
print_r($match);

输出:Array ( [0] => (15) [1] => [2] => 15 )

预期:Array ( [0] => [1] => 15 )

1 个答案:

答案 0 :(得分:3)

解决方案

也许你可以尝试类似的东西,

/([0-9]{4})?(?:\(([0-9]*)\))?/