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($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 = array();
preg_match($somePattern, $someSubject, $matches);
print_r($matches);
Am i just being paranoid?
The preg_match() function returns true if pattern matches otherwise, it returns false.
preg_match stops looking after the first match. preg_match_all , on the other hand, continues to look until it finishes processing the entire string. Once match is found, it uses the remainder of the string to try and apply another match.
preg_match() returns 1 if the pattern matches given subject , 0 if it does not, or false on failure. This function may return Boolean false , but may also return a non-Boolean value which evaluates to false .
The preg_match() function will tell you whether a string contains matches of a pattern.
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.
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:
$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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With