PHP 如何从右侧提取字符串


PHP how to extract string from the right side?

嗨,有这个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);

使用 explode() 并选择最后 3 个(或基于您的逻辑)部分。可以通过查找元素的数量来确定零件数

这将获取文件之后的所有内容:

$string = 'http://localhost/wpmu/testsite/files/2012/06/testimage.jpg';
preg_match('`files/(.*)`', $string, $matches);
echo $matches[1];

更新:但我认为Doug Owings的解决方案会快得多。

$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

我认为您只需要检查这个功能:

http://php.net/manual/en/function.substr.php

如果"http://localhost/wpmu/testsite/files/"部分稳定,那么您就知道要摆脱哪个部分。

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

$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";

不需要正则表达式:

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