PHP如何从右侧提取字符串?

PHP如何从右侧提取字符串?,php,regex,Php,Regex,嗨,有这个URL字符串,我需要提取可能使用正则表达式,但需要做它从右到左。例如: http://localhost/wpmu/testsite/files/2012/06/testimage.jpg 我需要摘录这一部分: 2012/06/testimage.jpg 如何做到这一点?先谢谢你 更新:因为URL中只有“文件”是常量,所以我想提取“文件”之后的所有内容。您需要检查的是这个函数,我认为: 如果“http://localhost/wpmu/testsite/files/“一部分是稳定

嗨,有这个URL字符串,我需要提取可能使用正则表达式,但需要做它从右到左。例如:

http://localhost/wpmu/testsite/files/2012/06/testimage.jpg
我需要摘录这一部分:

2012/06/testimage.jpg
如何做到这一点?先谢谢你


更新:因为URL中只有“文件”是常量,所以我想提取“文件”之后的所有内容。

您需要检查的是这个函数,我认为:


如果“http://localhost/wpmu/testsite/files/“一部分是稳定的,那么你就知道该去掉哪一部分了

使用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
$string = 'http://localhost/wpmu/testsite/files/2012/06/testimage.jpg';
preg_match('`files/(.*)`', $string, $matches);
echo $matches[1];
更新:
但我认为Doug Owings的解决方案会快得多。

您不一定需要使用正则表达式

$str = 'http://localhost/wpmu/testsite/files/2012/06/testimage.jpg';
$result = substr( $str, strpos( $str, '/files/') + 7);
不需要正则表达式:

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));
}

我喜欢爆炸的简单解决方案(正如骑士建议的):


有几种方法。您需要什么样的逻辑来界定哪些需要剥离,哪些保留?您可以使用
explode
函数,然后使用
sizeof($array)-someValue将其作为数组项。我认为这里唯一不变的是“文件”所以我猜我想提取文件后的所有内容是的,它不稳定,所以我的问题是从右边问的…谢谢你,但是我刚刚更新了帖子,意识到“文件”是唯一的常量…所以文件后的所有内容都是我需要的。只需删除
/files
之前的所有内容。更新了我的答案。正则表达式末尾的文件扩展名检查是确保您实际上只处理图像URI的好方法。看看修改后的代码。我想这个解决方案可能比正则表达式快得多。
$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";