为cdn集成按文件类型更改域regex


Domain change regex by file type for cdn integration

我希望能得到一些帮助,用PHP编写一个干净的正则表达式,将某些类型资产的域从可能包含多个资产(图像、javascript等)URL的字符串转换为

例如:

$string = 'Some content including image tags <img src="http://domain.com/image.png" /> and image urls http://domain.com/image.png and javascript links <script src="http://domain.com/funtimes.js"></script> and js urls http://domain.com/funtimes.js but not this image http://notthisdomain.com/nope.png';

正则表达式应更改位于的资产的域http://domain.com到http://cdndomain.com,但仅适用于扩展名为.png.jpg.gif.js.css的文件

上述所需的输出为

$string = 'Some content including image tags <img src="http://cdndomain.com/image.png" /> and image urls http://cdndomain.com/image.png and javascript links <script src="http://cdndomain.com/funtimes.js"></script> and js urls http://cdndomain.com/funtimes.js but not this image http://notthisdomain.com/nope.png';

更换

(?:http:'/'/domain.com)('S*?'.(?:png|jpg|gif|js|css))'b

带有

http://cdndomain.com'1

看到它在行动


这个想法是匹配你的域,后面跟着多个字符,后面跟着一个扩展名。将其替换为新域和组1中捕获的字符串的其余部分。
这里需要注意的三件重要事情:

  • 'S*(多个非空格字符)用于匹配此url的其余部分。重要的是不要使用.*["']*或类似的东西,就好像你得到了一个失败的匹配,然后有另一个扩展名为该扩展名的文件,中间字符串将包含在匹配中
  • ?让它变得懒惰,所以我们也不会在比赛之间介入
  • 末尾有单词边界('b),因此(例如)只有字符js的单词不会结束匹配,这是实际的扩展
$string = 'Some content including image tags <img src="http://domain.com/image.png" /> and image urls http://domain.com/image.png and javascript links <script src="http://domain.com/funtimes.js"></script> and js urls http://domain.com/funtimes.js but not this image http://notthisdomain.com/nope.png';
$file_types = "png|js|jpeg|jpg";
echo preg_replace ( "/http:'/'/domain.com([^'"']*($file_types))['"']/" , "http://cdn.domain.com$1" , $string);
# output:
# Some content including image tags <img src="http://cdn.domain.com/image.png" /> and image urls http://cdn.domain.com/image.png and javascript links <script src="http://cdn.domain.com/funtimes.js"></script> and js urls http://cdn.domain.com/funtimes.js but not this image http://notthisdomain.com/nope.png

它的工作方式是从匹配开始http://domain.com.然后它继续搜索,直到找到您定义的$file_types扩展中的一个,该扩展后面紧跟着一个双引号或一个单引号(['"'])。

如果在搜索扩展名的过程中的任何时候,它首先命中单引号或双引号([^'"']),我们可以推断出我们当前正在查找的URL没有我们正在查找的扩展名,因此我们在下一个URL重新开始搜索。