douzhuo1853 2012-04-21 10:51
浏览 53
已采纳

改变字符串中的所有图像

I'm using this line to change all images in my $comments string:

$comments = preg_replace("{<img\\s*(.*?)src=('.*?'|\".*?\"|[^\\s]+)(.*?)\\s*/?>}ims", '<a class ="gallery"rel="'.$pagelink.'"href=$2><img $1src=$2 $3 name= $2 $3  /></a>', $comments);

This works like a charm, it wraps it in <a> and adds some stuff. Now I need to alter the src path.

I want to add "mcith/mcith_" to every image in a string. i had a look at dom functions, but that didn't really seem to do the trick.

An image path looks like this: "/uploads/userdirs/admin(variable dir changes from user to user)/image.jpeg"

I want it to be this: "/uploads/userdirs/admin/mcith/mcith_image.jpeg"

On the similar question I got the answer using pathinfo, so I tried doing this:

if (preg_match('/<img.+src=[\'"](?P<src>.+?)[\'"].*>/i', $comments, $image) ) {
   $imagedir = $image['src'];
   $pathchange = pathinfo($imagedir);
   $comments = $pathchange['dirname'] . '/mcith/mcith_' . $pathchange['basename'];
}

But that doesn't work as I want it to as it messes up my entire string instead, text and all. I think the solution is in the preg_replace line, but can't figure out how to add stuff to the src on that line.

  • 写回答

2条回答 默认 最新

  • doushao8399 2012-04-21 13:18
    关注

    Is this what you need?

    <?php
    $comment = '<img src="/uploads/userdirs/admin-something/image.jpeg" />
    <div>text</div>
    <img src="/uploads/userdirs/admin-another/coffee.png" />
    ';
    $comment = preg_replace('@(<img.+src=[\'"]/uploads/userdirs/admin)(?:.*?/)(.+?)\.(.+?)([\'"].*?>)@i', '$1/mcith/mcith_$2.$3$4', $comment);
    echo $comment;
    

    See if it helps. Try online: http://codepad.org/TT9rH6IX

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

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100