As for practice and later development, i'm working on a PHP router. For this router, my mapped routes could have parameters in them, a route looks like this:
/home/{i:pageNum}/{s:userName}
There are now 2 variables in this route:
For capturing this data, i wrote this regular expression:
{((?<type>\D):)?(?<name>[a-zA-Z_-ÿ][a-zA-Z0-9_-ÿ]+)}
This works great, but the only problem with it is that it only captures the first variable only.
It does only capture more of these matches when I put a new route on a new line.
I tried capturing the whole regular expression by surrounding it by (
's and )
's. This did not work.
How can I make this regular expression so that it captures more matches on one line of text?
For calling this regular expression, I use the following PHP function:
preg_match("/{((?<type>\D):)?(?<name>[a-zA-Z_-ÿ][a-zA-Z0-9_-ÿ]+)}/", "/home/{i:pageNum}/{s:userName}", $matches);
Just use preg_match_all()
and PREG_SET_ORDER
:
preg_match_all("/{((?<type>\D):)?(?<name>[a-zA-Z_-ÿ][a-zA-Z0-9_-ÿ]+)}/",
"/home/{i:pageNum}/{s:userName}",
$matches,
PREG_SET_ORDER);
Then:
foreach($matches as $match) {
echo $match['name'] . ' = ' . $match['type'];
}
Using the default PREG_PATTERN_ORDER
you could do:
$matches = array_combine($matches['name'], $matches['type']);
foreach($matches as $name => $type) {
echo "$name = $type";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.