(PHP) 在 preg_match 中获取 null 而不是获取空字符串
我有以下代码:
$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
)
问题是 $match[1]、$match[2]、$match[3] 和 match[4] 是 string(0)
,在那里有什么方法可以修改 $pattern
以获得 null
而不是 string(0)
?
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[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)
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,这在 PHP 中是不可能的。 preg_match() 函数仅处理字符串,null 是一种完全不同的数据类型。
不过,将其转换为您想要的内容很简单。在 PHP 5.3 中,您可以使用带有 array_walk() 的匿名函数来迭代数组,然后使用缩短了三元运算。
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.