【问题标题】:Replace image src in php using regex使用正则表达式替换 php 中的图像 src
【发布时间】:2018-07-15 00:37:45
【问题描述】:

我想替换一个包含图片标签的字符串 像这样

img src="images/Selection_005.png"
img src="images/Selection_006.png"

进入这个

img src="/documents/20143/0/Selection_005.png"
img src="/documents/20143/0/Selection_006.png"

我只是想修改图像的路径。 如何使用正则表达式在 php 中创建它?

我可以提供示例代码吗?

【问题讨论】:

  • 为什么是正则表达式?这是您需要的简单 str_replace 。你应该在你的问题中包含你的尝试。
  • 您自己尝试过什么,还是只需要/想要免费的示例代码?
  • 发现这个问题的每个人都可能搜索$string = preg_replace('(src="(.*?)")','src="newimage.png" data-echo="$1"', $string);

标签: php regex preg-replace str-replace


【解决方案1】:

当它是静态“查找”时,请改用 str_replace,它会更快并且需要更少的 RAM。

$arr =['img src="images/Selection_005.png"',
       'img src="images/Selection_006.png"'];

$find = "images";
$replace ="/documents/20143/0";

Foreach($arr as $link){
    Echo str_replace($find, $replace, $link) ."\n";
}

输出

img src="/documents/20143/0/Selection_005.png"
img src="/documents/20143/0/Selection_006.png"

https://3v4l.org/0ZT9e

【讨论】:

  • 为了澄清,我有一个这样的字符串 $content = '

    Lorem ipsum

    ';我想找到该字符串中的所有图像并替换我想要发生的图像的路径
  • @FalconRyu 是吗?
  • 所以我在想我是否必须为此使用正则表达式
  • 仍然不需要正则表达式。阅读 str_replace 的手册。 php.net/str_replace 示例:3v4l.org/T33EP
  • 谢谢!尽管我做了一些更改,但它对我有用3v4l.org/bTSgD
猜你喜欢
  • 2012-04-10
  • 2012-05-26
  • 2015-11-08
  • 2014-03-29
  • 2019-06-03
  • 1970-01-01
  • 2013-12-09
  • 2011-02-21
  • 1970-01-01
相关资源
最近更新 更多