Ron
Ron

Reputation: 394

Replace only the path of image usig preg_replace in php

I am using preg_replace to alter the image path only except image name like:

<img src="http://www.ByPasspublishing.com/uploadedImages/TinyUploadedImage/SOC_Aggression_Define_Fig Territorial Aggression.jpg" />

to

Below is the code I have tried but it replace the total path. Please help me to solve this problem:

$html = preg_replace('/<img([^>]+)src="([^"]+)"/i','<img\\1src="newfolder"',$slonodes[0]->SLO_content);

Another thing is that $slonodes[0]->SLO_content returns an HTML content within which I have to find the image and replace the path of that image so the path will not be same.

Thanks in advance.

Upvotes: 1

Views: 805

Answers (2)

Kevin
Kevin

Reputation: 41885

Alternatively, you could use an HTML Parser for this task, DOMDocument in particular:

$html = '<img src="http://www.ByPasspublishing.com/uploadedImages/TinyUploadedImage/SOC_Aggression_Define_Fig Territorial Aggression.jpg" />';
$dom = new DOMDocument;
libxml_use_internal_errors(true);
$dom->loadHTML($html);
libxml_clear_errors();

$img = $dom->getElementsByTagName('img')->item(0);
$new_src = 'newfolder/' . basename($img->getAttribute('src'));
$img->setAttribute('src', $new_src);
echo $dom->saveHTML($img);

Upvotes: 1

Marco Mura
Marco Mura

Reputation: 582

Why use regex? O.o

You can do something like this:

$path = "http://www.ByPasspublishing.com/uploadedImages/TinyUploadedImage/SOC_Aggression_Define_Fig Territorial Aggression.jpg";
$pathNew = "newfolder/".substr(strrchr($path, "/"), 1);
print $pathNew;

I cut on the last "/" char and then concatenate Strings and chars to obtain your desired output.

Upvotes: 0

Related Questions