您好有这个 URL 字符串,我可能需要使用正则表达式来提取它,但需要从右侧到左侧进行提取。例如:
http://localhost/wpmu/testsite/files/2012/06/testimage.jpg
我需要提取这部分:
2012/06/testimage.jpg
如何才能做到这一点?提前致谢...
更新:由于只有 URL 中的“文件”是常量,我想提取“文件”之后的所有内容。
您不一定需要使用正则表达式。
$str = 'http://localhost/wpmu/testsite/files/2012/06/testimage.jpg';
$result = substr( $str, strpos( $str, '/files/') + 7);
这将为您提供文件后的所有内容:
$string = 'http://localhost/wpmu/testsite/files/2012/06/testimage.jpg';
preg_match('`files/(.*)`', $string, $matches);
echo $matches[1];
更新: 但我认为 Doug Owings 的解决方案会快很多。
使用 explode() 并选择最后 3 个(或基于您的逻辑)部分。零件的数量可以通过找到元素的数量来确定
$matches = array();
$string = 'http://localhost/wpmu/testsite/files/2012/06/testimage.jpg';
preg_match('/files\/(.+)\.(jpg|gif|png)/', $string, $matches);
echo $matches[1]; // Just the '2012/06/testimage.jpg' part
不需要正则表达式:
function getEndPath($url, $base) {
return substr($url, strlen($base));
}
此外,通过指定级别返回 url 路径的结尾部分的更通用的解决方案:
/**
* Get last n-level part(s) of url.
*
* @param string $url the url
* @param int $level the last n links to return, with 1 returning the filename
* @param string $delimiter the url delimiter
* @return string the last n levels of the url path
*/
function getPath($url, $level, $delimiter = "/") {
$pieces = explode($delimiter, $url);
return implode($delimiter, array_slice($pieces, count($pieces) - $level));
}
我喜欢爆炸的简单解决方案(如 knightrider 建议的那样):
$url="http://localhost/wpmu/testsite/files/2012/06/testimage.jpg";
function getPath($url,$segment){
$_parts = explode('/',$url);
return join('/',array_slice($_parts,$segment));
}
echo getPath($url,-3)."\n";
您需要检查的是我认为的这个功能:
http://php.net/manual/en/function.substr.php
如果“http://localhost/wpmu/testsite/files/”部分是稳定的,那么你就知道要去掉哪个部分。