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

时间:2012-07-01 17:40:39

标签: php regex

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

http://localhost/wpmu/testsite/files/2012/06/testimage.jpg

我需要提取这部分内容:

2012/06/testimage.jpg

如何做到这一点?提前谢谢......

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

7 个答案:

答案 0 :(得分:5)

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

$str = 'http://localhost/wpmu/testsite/files/2012/06/testimage.jpg';
$result = substr( $str, strpos( $str, '/files/') + 7);

答案 1 :(得分:2)

使用explode()并选择最后3个(或基于您的逻辑)部分。找不到元素

可以确定零件数量

答案 2 :(得分:2)

这将为您提供文件后的所有内容:

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

<强>更新 但我认为Doug Owings的解决方案会更快。

答案 3 :(得分:0)

我认为你需要检查的是这个功能:

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

如果“http:// localhost / wpmu / testsite / files /”部分是稳定的,那么你知道哪个部分要摆脱。

答案 4 :(得分:0)

$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

答案 5 :(得分:0)

不需要正则表达式:

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

答案 6 :(得分:0)

我喜欢爆炸的简单解决方案(由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";