doumizhi0809 2017-03-21 11:14
浏览 36
已采纳

替换长字符串中文件名中每个句点的出现次数

$text = 'This is a long text containing different image paths like <img src="/site/assets/files/5136/image1.jpg" width="750" />. The text may contain more than one image, here's another one: <img src="/site/assets/files/5136/image1.1.jpg" width="750" />';

Please consider the example text above. I'm looking for a good way to replace period characters in filenames inside a string, that may contain multiple filenames. 'image1.1.jpg' should become 'image1_1.jpg', so the period should be replaced by an underscore. Only period characters that belong to a filename should be replaced. The filename always looks like this:

/site/assets/files/5136/image1.1.jpg

/site/assets/files/425/image1.jpg

/site/assets/files/6524/image2.x.png

The bold parts are variable, the rest of the path is always the same. A filename may or may not contain a period. The extension is .jpg or .png and I only want to target images.

I would like to use PHP to do this.

  • 写回答

2条回答 默认 最新

  • dongqian0763 2017-03-21 11:36
    关注

    Untested:

    $new_text = preg_replace_callback('/(\/site\/assets\/files\/[^\/]+\/)([^\/]+)(\.[a-z0-9]+)/i', function ($matches) {
        return $matches[1] . str_replace('.', '_', $matches[2]) . $matches[3];
    }, $text);
    

    The regex matches all paths beginning with /site/assets/files followed by one more path segment plus a filename ending with an extension separated by a single dot (like .jpg, but not .tar.gz). The match has three groups: the folder path ($matches[1]), the filename ($matches[2]) and the extension ($matches[3]). str_replace is used to replace all dots (.) in $matches[2] with underscores (_).

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

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?