从PHP中的字符串中提取正则表达式的最后一个实例
I have a URL that is in the following structure: http://somewebsite.com/directory1/directory2/directory3...
I'm trying to get the last directory name from this url, but the depth of the url isn't always constant so i don't think i can use a simple substr or preg_match call - is there a function to get the last instance of a regular expression match from a string?
我有一个以下结构的网址: http://somewebsite.com/directory1/directory2/directory3 ... p>
我正在努力获取 这个网址的最后一个目录名称,但网址的深度并不总是常数,所以我不认为我可以使用简单的substr或preg_match调用 - 是否有一个函数来获取正则表达式匹配的最后一个实例 串? p> div>
Just use:
basename( $url )
It should have the desired effect
Torben's answer is the correct way to handle this specific case. But for posterity, here is how you get the last instance of a regular expression match:
preg_match_all('/pattern/', 'subject', $matches, PREG_SET_ORDER);
$last_match = end($matches); // or array_pop(), but it modifies the array
$last_match[0]
contains the complete match, $last_match[1]
contains the first parenthesized subpattern, etc.
Another point of interest: your regular expression '/\/([^/])$/'
should work as-is because the $
anchors it to the end.