2017-07-01 29 views
0

我需要从文件名url的起始处删除一个子字符串。如何删除url中文件名的一部分

我需要删除的子字符串总是一系列数字然后连字符然后字gallery然后另一个连字符。

例如2207-gallery-2208-gallery-1245-gallery-

我怎样才能改变这样的:

http://img.pass.com:7710/img.pass.com/img-1/2207-gallery-25171-content_gallery-1428380843.jpg 

这样:

http://img.pass.com:7710/img.pass.com/img-1/25171-content_gallery-1428380843.jpg 

要替换的子串始终是不同的。

+0

请给出更多的说明:是删除的文本总是'2207-gallery-'?或者这只是一个例子? –

+0

@HamzaAbdaoui更新 – ATIKON

+0

因此它可以是'2208-gallery-','1245-gallery-'等......? –

回答

2

这将匹配1个或多个数字然后连字符,然后 “库”,那么连字符:

图样:(Demo

/\d+-gallery-/ 

PHP代码:(Demo

$image='http://img.pass.com:7710/img.pass.com/img-1/2207-gallery-25171-content_gallery-1428380843.jpg'; 
echo preg_replace('/\d+-gallery-/','',$image); 

输出:

http://img.pass.com:7710/img.pass.com/img-1/25171-content_gallery-1428380843.jpg 

这是你的非正则表达式的方法:

echo substr($image,0,strrpos($image,'/')+1),substr($image,strpos($image,'-gallery-')+9); 
1

PHP做到这一点:

function renameURL($originalUrl){ 
    $array1 = explode("/", $originalUrl); 
    $lastPart = $array1[count($array1)-1];//Get only the name of the image 
    $array2 = explode("-", $lastPart); 
    $newLastPart = implode("-", array_slice($array2, 2));//Delete the first two parts (2207 & gallery) 
    $array1[count($array1)-1] = $newLastPart;//Concatenate the url and the image name 
    return implode("/", $array1);//return the new url 
} 
//Using the function : 
$url = renameURL($url); 

DEMO

+1

虽然正则表达式可能比一些非正则表达式方法慢,但我觉得编写如此多的代码并利用7个函数而不是单个preg_replace()调用非常有吸引力。这是PHP设计人员为其创建正则表达式函数的原因。 – mickmackusa

1
function get_numerics ($str) { 
    preg_match_all('/\d+/', $str, $matches); 
    return $matches[0]; 
} 

$one = 'http://img.pass.com:7710/img.pass.com/img-1/2207-gallery-25171-content_gallery-1428380843.jpg'; 


$pos1 = strpos($one, get_numerics($one)[3]); 
$pos2 = strrpos($one, '/')+1; 
echo ((substr($one, 0, $pos2).substr($one, $pos1))); 

看到它帮助你。

+0

如果您打算使用正则表达式,请单独使用它。如果你不想使用正则表达式或其他速度原因,请不要使用任何正则表达式函数。用同样的方法做这两件事似乎很愚蠢。 – mickmackusa