I'm hoping for some help writing with a clean regex in PHP to convert the domain of certain kinds of assets from a string potentially containing urls of multiple assets (images, javascripts etc.)

我希望在PHP中使用干净的正则表达式来帮助编写某些类型的资源的域,从可能包含多个资产的URL(图像,javascripts等)的字符串转换

For example:

$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';

The regex should change the domain for assets at http://domain.com to http://cdndomain.com, but only for files with the extensions: .png .jpg .gif .js .css

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

The desired output for the above would be

以上所需的输出将是

$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';

2 个解决方案

#1


1

Replace

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

with

http://cdndomain.com\1

See it in action

看到它在行动


The idea is to match your domain, followed by multiple characters, followed by one of the extensions. Replace that with the new domain and the remainder of the string captured in group 1.
Three important things to note here:

  • \S* (multiple non-space characters) is used for matching the rest of this url. It is important not to use .* or ["']* or something like that as if you get a fail match, and later there is another file with that extension the in between string will be included in the match.
  • \ S *(多个非空格字符)用于匹配此网址的其余部分。重要的是不要使用。*或[“'] *或类似的东西,就像你得到一个失败的匹配,后来有另一个带有该扩展名的文件,字符串之间将包含在匹配中。

  • It is made lazy with ? so that we also don't get in between matches.
  • 这是懒惰吗?这样我们也不会介入比赛之间。

  • There is word boundary (\b) at the end so that a word that just has the characters js in it (for example) wont end the match and this is the actual extension.
  • 在末尾有单词边界(\ b),这样一个只有字符js的单词(例如)就不会结束匹配,这就是实际的扩展名。

更多相关文章

  1. 查找具有特定数据字符串的数组并返回其具有的另一个数据字符串
  2. 在php中,从字符串中删除逗号后的所有内容
  3. 如何通过PHP将HTML页面作为字符串获取?
  4. php 基本的常用字符串函数
  5. 用PHP计算字符串中元音的简单方法?
  6. 将DOMDocument中的特定元素导出为字符串
  7. PHP实现字符串转换成查询语句
  8. mysql 判断null 和 空字符串
  9. mysql如何判断一个字符串是否包含另外一个字符串?

随机推荐

  1. Android中 ToggleButton【状态切换按钮】
  2. Android(安卓)开发四大天王 四大组件 (很
  3. Android UI之TextView实现跑马灯效果
  4. 第16天android:看android的书籍
  5. FAQ_15_android Imageview ImageButton B
  6. [Android] ExpandableListView 子目录点
  7. android shape用法
  8. Android内存管理机制
  9. Android 4.0.3 CTS 测试
  10. android系统工具之 draw9patch超详细教程