2014-04-16 20 views
0

我必須要改變的URL看起來像Chaning圖像的URL用正則表達式

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. 十分之二千零十一/
  3. PiaggioBeverly-001-106x106.jpg

然後切斷來自第三組的分辨率串(106x106),除掉在末端連字符的下一個和移動分辨率第二。任何想法如何使用像preg_replace這樣的東西來完成?

回答

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
<?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) «+»