dongzhan1948 2017-01-13 04:00
浏览 284
已采纳

正则表达式在url中获取文件类型

I am using a converter that accepts Regex to do a mass "search and replace" in a database to change all .png to .jpg. Consider the following where a link to an image is mixed in with a lot of HTML code (simplified example):

bunch_of_text_http:// somewebsite.com/somepath/somefile.png_bunch_of_text

The "bunch_of_text" and "some-x" are all variables.

For clarification, the only .png's I need changed must follow a mostly prescribed URL. For example, I need to replace all .png's on the example.com domain but not on other domains. Here's another example:

Convert: http://example.com/images/XX/YY/filename.png to http://example.com/images/XX/YY/filename.jpg

WHERE

XX and YY are variables and may be at any level of depth in the folder structure.

But ignore any other domain other than example.com.

The code on the backend is written in PHP.

I need one line of Regex code to return only the ".png" text so my script can replace that with ".jpg". Any help is greatly appreciated.

  • 写回答

3条回答 默认 最新

  • duanmei4362 2017-01-13 05:01
    关注
    $url = "http://example.com/images/XX/YY/filename.png";
    $result = preg_replace(';(http://example.com/images/.*?/.*?/.*?)\.png;', '$1.jpg', $url);
    echo $result;
    

    Some regular expression explanation: https://regex101.com/r/2ZDzq0/1

    Note I've replaced the usual / delimiter with ; because it's easier when working with URLs.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)