2017-03-28 38 views
0

我有無數的URL看起來像這樣(1),有的看起來像這樣(2)的preg_match一定網址 - PHP

1)http://URL.com/gallery/image.png

2)http://URL.com/gallery/#/image.png

其中#表示編號的文件夾。

我想補充thumb_到URL,所以它看起來是這樣的:

1)http://URL.com/gallery/thumb_image.png

2)http://URL.com/gallery/#/thumb_image.png

我會怎麼做呢?

要考慮的一件事是圖像文件之前的文件夾可以是任何數字,並且圖像文件並不總是被命名爲「image.png」。我以此爲例。

+0

所以,你要Web服務器的重寫規則,或實際編程方式重命名文件? –

回答

0

您可以使用一個簡單的正則表達式是這樣的:

(\w+\.\w+)$ 

隨着替換字符串:

thumb_\1 

Working demo

PHP代碼

$re = '/(\w+\.\w+$)/m'; 
$str = 'http://URL.com/gallery/image.png 
http://URL.com/gallery/#/image.png'; 
$subst = 'thumb_\\1'; 

$result = preg_replace($re, $subst, $str); 

echo "The result of the substitution is ".$result; 
+0

這工作完美。 – stylusss

0

你可以使用的preg_replace函數

<?PHP 
$input_lines="http://URL.com/gallery/#/image.png"; 
ECHO preg_replace("/\w+\.\w+$/", "thumb_$0", $input_lines); 
?>