0

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.

Community
  • 1
  • 1
Havihavi
  • 652
  • 1
  • 9
  • 26

2 Answers2

1

Try this solution...Hope this will help you

    if(preg_match_all('/(<img[^>]*>)/Ui', $comments, $match, PREG_OFFSET_CAPTURE)){ //loop through all img tags 
        $shiftOffset = 0;
        for($i=0; $i<count($match[1]); $i++){  //loop to execute no.of times img tag found
        if($i){ // do not change offset for single or first occurence
                $shiftOffset += substr_count($match[1][$i-1][0], "<img ");  //count the img tag
                $match[1][$i][1] += $shiftOffset;
               }
        $sub = "form your new img src that is to replaced for old img src"; 
        $comments = str_replace($match[1][$i][0],$sub,$comments); //change the original img tag with our img tag
       }
   }
nithi
  • 3,725
  • 2
  • 20
  • 18
1

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

galymzhan
  • 5,505
  • 2
  • 29
  • 45