Adjustment of regular expression matching rules in PHP (allowing a certain capture subgroup is empty)
1. The existing PHP code is implemented as follows
// $va = 'internal://all_collectionss/';
$va = 'internal://all_collectionss/1';
$matches = [];
if (preg_match('#internal://([^/]+)s/([^/]+)#', $va, $matches)) {
$resource = strtolower($matches[1]);
$resourceId = $matches[2];
}
2. Open:https://regex101.com/, the matching is successful, and the result is as follows. as shown in Figure 1
Match 1 0-29 internal://all_collectionss/1
Group 1 11-26 all_collections
Group 2 28-29 1
3. Now expect that internal://all_collections/ can also match. Tip: Your regex doesn’t match the theme string. as shown in Figure 2
Your regular expression does not match the subject string.
Try launching the debugger to find out why.
4. Characters with special meanings in regular expressions are called metacharacters, and the commonly used metachars are: * quantifiers, 0 or more matches; + quantifiers, 1 or more matches. Since the last / after the allowed is empty, you should adjust + to *. #internal://([^/]+)s/([^/]*)# Both cases can be matched successfully. Figure 3, Figure 4
5. The final PHP code is implemented as follows
// $va = 'internal://all_collectionss/';
$va = 'internal://all_collectionss/1';
$matches = [];
if (preg_match('#internal://([^/]+)s/([^/]*)#', $va, $matches)) {
$resource = strtolower($matches[1]);
$resourceId = $matches[2];
}



