Preg_match某个URL - PHP

时间:2017-03-28 16:09:56

标签: php regex preg-match

我有无数的网址看起来像(1),有些看起来像这样(2)

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

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

其中#代表编号文件夹。

我想将thumb_添加到网址中,因此它看起来像这样:

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

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

我该怎么做?

要考虑的一件事是图像文件之前的文件夹可以是任何数字,图像文件并不总是命名为“image.png”。我这样做了。

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分:0)

您可以使用preg_replace函数

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