preg_match
accepts a $matches
argument as a reference. All the examples I've seen do not initialize it before it's passed as an argument. Like this:
preg_match接受$ matches参数作为引用。我见过的所有例子都没有在它作为参数传递之前初始化它。像这样:
preg_match($somePattern, $someSubject, $matches);
print_r($matches);
Isn't this error-prone? What if $matches
already contains a value? I would think it should be initialized to an empty array before passing it in as an arg. Like this:
这不容易出错吗?如果$ matches已包含值,该怎么办?我认为应该在将它作为arg传递之前初始化为空数组。像这样:
$matches = array();
preg_match($somePattern, $someSubject, $matches);
print_r($matches);
Am i just being paranoid?
我只是偏执狂吗?
2 个解决方案
#1
6
There is no need to initialise $matches as it will be updated with the results. It is in effect a second return value from the function.
无需初始化$ match,因为它将随结果一起更新。它实际上是函数的第二个返回值。
#2
1
as Chris Lear said you don't need to initialize $matches
. But if your pattern contains a capture group you want to use later, it is better to write:
正如Chris Lear所说,你不需要初始化$ match。但是如果您的模式包含您希望稍后使用的捕获组,则最好编写:
$somePattern = '/123(456)/';
if (preg_match($somePattern, $someSubject, $matches)) {
print_r($matches[1]);
}
to avoid the error of undefined index in the result array. However, you can use isset($matches[1])
to check if the index exists.
避免结果数组中未定义索引的错误。但是,您可以使用isset($ matches [1])来检查索引是否存在。
#1
6
There is no need to initialise $matches as it will be updated with the results. It is in effect a second return value from the function.
无需初始化$ match,因为它将随结果一起更新。它实际上是函数的第二个返回值。
#2
1
as Chris Lear said you don't need to initialize $matches
. But if your pattern contains a capture group you want to use later, it is better to write:
正如Chris Lear所说,你不需要初始化$ match。但是如果您的模式包含您希望稍后使用的捕获组,则最好编写:
$somePattern = '/123(456)/';
if (preg_match($somePattern, $someSubject, $matches)) {
print_r($matches[1]);
}
to avoid the error of undefined index in the result array. However, you can use isset($matches[1])
to check if the index exists.
避免结果数组中未定义索引的错误。但是,您可以使用isset($ matches [1])来检查索引是否存在。