(PHP) Getting null in a preg_match instead of getting a empty string
I have the following code:
$pattern = '(([a-z]{2})/)?(([a-z]{3,})/)?(\d{4}+)(/(\d{2})(/(\d{2}))?)?';
preg_match('#^' . $pattern . '$#i', '2010/12/01', $match);
$match = Array (
[0] => 2010/12/01
[1] =>
[2] =>
[3] =>
[4] =>
[5] => 2010
[6] => /12/01
[7] => 12
[8] => /01
[9] => 01
)
The problem is that $match开发者_StackOverflow社区[1], $match[2], $match[3] and match[4] are string(0)
, is there any way to modify the $pattern
in order to get null
instead of string(0)
?
No, that is not possible in PHP. The preg_match() function only deals with strings and null is an entirely other data type.
Converting this to what you want is simple though. In PHP 5.3 you can use an anonymous function with array_walk() to iterate over the array and then update your values with a shortened ternary operation.
array_walk($array, function(&$val) { $val = $val ?: null; });
精彩评论