简体   繁体   中英

PHP regex to match groups in string

i have a PHP project that uses routing this passes the url requested feedback/services/mytoken i then have a regex that detects the parts o pass to the script with this /^feedback(\\/(?P<form>.*))(\\/(?P<token>.*))/U example RegEx Test this works fine for now, but i have realized that i will come into some issues when the url is feedback/service it wont pick it up.

// working
$request = 'feedback/services/mytoken';
$regex = '/^feedback(\/(?P<form>.*))(\/(?P<token>.*))/U';
// returns
$returns = [
"form" => 'services',
"token" => "mytoken" 

];

// not working
$request = 'feedback/services';
$regex = '/^feedback(\/(?P<form>.*))(\/(?P<token>.*))/U';
// expected returns
$returns = [
"form" => 'services'
];

i want to be able to capture the groups correctly but i'm not sure of the right way to go about it. also i want to be able to pick it up if only part of it matches ie feedback/services is sent, it will group form to services and not match token

You may use

'~^feedback(?:/(?P<form>[^/]*))?(?:/(?P<token>[^/]*))?~'

See the regex demo

If no more text should appear on the right, add $ at the end of the regex:

'~^feedback(?:/(?P<form>[^/]*))?(?:/(?P<token>[^/]*))?$~'

Details

  • ^ - start of input
  • feedback - literal string
  • (?:/(?P<form>[^/]*))? - an optional non-capturing group:
    • / - a / char (no need to escape since ~ is used a regex delimiter char)
    • (?P<form>[^/]*) - Group "form": any 0 or more chars other than /
  • (?:/(?P<token>[^/]*))? - an optional non-capturing group:
    • / - a / char
    • (?P<token>[^/]*) - Group "token": any 0 or more chars other than /
  • $ - end of input.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM