我有这个网址:
http://localhost/cms/uploads/files/1/images/hd-wallpaper-40.jpg
并需要转换为:(删除1之前的所有网址)
1/images/hd-wallpaper-40.jpg
编辑:
http://localhost/cms/uploads/files/
是动态的,所以也许:http://localhost/uploads/files/
如何使用php转换此网址?
答案 0 :(得分:5)
我不知道您需要的规则/条件,但这是一种方式:
$url = parse_url('http://localhost/cms/uploads/files/1/images/hd-wallpaper-40.jpg');
echo str_replace('/cms/uploads/files/', '', $url['path']);
更新:
如果images
是静态的:
$url = parse_url('http://localhost/cms/uploads/files/1/images/hd-wallpaper-40.jpg');
preg_match('/[0-99999]\/.*/', $url['path'], $matches);
echo $matches[0];
答案 1 :(得分:2)
您可以使用parse_url函数在主机(在本例中为localhost)之后获取whatevers,然后使用explode路径slice an array和implode返回:
$str = "http://localhost/cms/uploads/files/1/images/hd-wallpaper-40.jpg";
$parsed_url = parse_url($str);
echo implode("/", array_slice(explode("/", $parsed_url['path']),4));
答案 2 :(得分:0)
一个简单的解决方案可能是;
$basepath = 'http://localhost/cms/uploads/files/';
$url = 'http://localhost/cms/uploads/files/1/images/hd-wallpaper-40.jpg';
if (strncmp($basepath, $url, strlen($basepath)) == 0 ) {
$result = substr($url, strlen($basepath));
} else {
$result = false;
}
echo $result;
答案 3 :(得分:0)
试试这个,带有'/ 1 /'的动态内容将完美运行
$str = "http://localhost/cms/uploads/files/1/images/1/hd-wallpaper-40.jpg";
//url as string
$pos = strpos($str,'1'); //position of first '1' in url
$len = strlen($str); //length of url string
$str1 = substr($str,$pos,($len-$pos)); //substring from '1' onwards
也有一些缺点。如果之前出现'1',我的意思是url =“http://localhost/ cms1 / uploads / files / 1 / images,它会给出错误的结果。 如果使用动态作者ID而不是1,则将作者ID保存为变量并插入strpos()。下面的内容更准确,您也可以使用动态authorID。
$str = "http://localhost/cms/uploads/files/1/images/1/hd-wallpaper-40.jpg";
//url as string
$authid = 1; //author id
$searchstring = '/'.$authid.'/'; // create a search string '/1/'
$pos = strpos($str,$searchstring); //position of first '/1/' in url
$len = strlen($str); //length of url string
$str1 = substr($str,$pos+1,($len-$pos)); //substring from '1' onwards