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 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab