使用正则表达式更改图像URL

时间:2014-04-16 17:13:13

标签: regex url url-rewriting

我必须更改一个看起来像

的网址
http://my-assets.s3.amazonaws.com/uploads/2011/10/PiaggioBeverly-001-106x106.jpg

采用这种格式

http://my-assets.s3.amazonaws.com/uploads/2011/10/106x106/PiaggioBeverly-001.jpg

我知道我需要创建一个正则表达式模式,将初始URL分成三组:

  1. http://my-assets.s3.amazonaws.com/uploads/
  2. 2011/10 /
  3. PiaggioBeverly-001-106x106.jpg
  4. 然后从第三组中删除分辨率字符串(106x106),最后删除连字符并将分辨率移到第二组旁边。知道如何使用像preg_replace这样的东西来完成它吗?

3 个答案:

答案 0 :(得分:1)

模式如下(输入uploads/2011/10/PiaggioBeverly-001-106x106.jpg

^(.*/)(.+?)(\d+x\d+)(\.jpg)$

小组将按如下方式举行:

$1 = uploads/2011/10/
$2 = PiaggioBeverly-001-
$3 = 106x106
$4 = .jpg

现在根据您的需要重新排列。您可以查看此示例from online

正如您所提到的preg_replace(),如果它在PHP中,您可以使用preg_match()

答案 1 :(得分:1)

<?php

$oldurl = "http://my-assets.s3.amazonaws.com/uploads/2011/10/PiaggioBeverly-001-106x106.jpg";

$newurl = preg_replace('%(.*?)/(\w+)-(\w+)-(\w+)\.(\w+)%sim', '$1/$4/$2-$3.jpg', $oldurl);



echo $newurl;
#http://my-assets.s3.amazonaws.com/uploads/2011/10/106x106/PiaggioBeverly-001.jpg
?>

DEMO

<强>说明

Options: dot matches newline; case insensitive; ^ and $ match at line breaks

Match the regular expression below and capture its match into backreference number 1 «(.*?)»
   Match any single character «.*?»
      Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character “/” literally «/»
Match the regular expression below and capture its match into backreference number 2 «(\w+)»
   Match a single character that is a “word character” (letters, digits, and underscores) «\w+»
      Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the character “-” literally «-»
Match the regular expression below and capture its match into backreference number 3 «(\w+)»
   Match a single character that is a “word character” (letters, digits, and underscores) «\w+»
      Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the character “-” literally «-»
Match the regular expression below and capture its match into backreference number 4 «(\w+)»
   Match a single character that is a “word character” (letters, digits, and underscores) «\w+»
      Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the character “.” literally «\.»
Match the regular expression below and capture its match into backreference number 5 «(\w+)»
   Match a single character that is a “word character” (letters, digits, and underscores) «\w+»
      Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»

答案 2 :(得分:1)

搜索:(.*\/)(\w+-\d+)-(.*?)\.

并替换为:\1\3/\2.

演示:http://regex101.com/r/fX7gC2