简体   繁体   中英

Extract Key from URL with Preg_Match in PHP

I haves this URL https://test.com/file/5gdxyYpb#_FWRc4T12baPrppZIwVQ5i18Sq16f7TXU82LJwY_BjE

I need to create with preg_mach this condition:

$match[0]=5gdxyYpb#_FWRc4T12baPrppZIwVQ5i18Sq16f7TXU82LJwY_BjE

$match[1]=5gdxyYpb

$match[2]=_FWRc4T12baPrppZIwVQ5i18Sq16f7TXU82LJwY_BjE

I try difference pattern the mos closed was this one. e\/(.*?)\#(.*) .

Please any recommendation. (If necessary in Preg_Match).

Thank you,

You might use 2 capturing groups and make use of \K to not match the first part of the url to get the desired matches.

https?://.*/\K([^#\s]+)#(\S+)
  • https?:// Match the protocol with optional s, then ://
  • .*/ Match until the last occurrence of /
  • \K Forget what is matched until here
  • ([^#\s]+) Capture group 1 , match 1+ occurrences of any char except a # or whitespace char
  • # Match the #
  • (\S+) Capture group 2 , match 1+ occurrences of a non whitespace char

Regex demo | Php demo

$url = "https://test.com/file/5gdxyYpb#_FWRc4T12baPrppZIwVQ5i18Sq16f7TXU82LJwY_BjE";
$pattern = "~https?://.*/\K([^#]+)#(.*)~";
$res = preg_match($pattern, $url, $matches);
print_r($matches);

Output

Array
(
    [0] => 5gdxyYpb#_FWRc4T12baPrppZIwVQ5i18Sq16f7TXU82LJwY_BjE
    [1] => 5gdxyYpb
    [2] => _FWRc4T12baPrppZIwVQ5i18Sq16f7TXU82LJwY_BjE
)

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