Reputation: 25945
I am wondering if it's possible to get a regex match in PHP by only using one statement? This question is more of a challenge to see if this is possible.
Right now you have to do something like this:
preg_match('#(\d+)$#', $subject, $match);
echo $match[1];
How do I access $match
with one statement, instead of two?
I don't want to use preg_replace
.
If it's possible with a closure, the better. I love fancy code.
Upvotes: 1
Views: 451
Reputation: 46300
I don't think it's possbile. the third argument $matches
is always an array. From the PHP docs:
If matches is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on.
Source: http://www.php.net/manual/en/function.preg-match.php
If you have a lot of regexes that only have one group of capturing parentheses, you could make a shortcut function for your purpose:
function preg_match_one($regex, $subject) {
if(preg_match($regex, $subject, $matches)) {
return $matches[1];
}
else {
return false;
}
}
Upvotes: 3