Snooze
Snooze

Reputation: 217

preg_replace src img from text

I'm looking for a way to change all my src of img from a text.

Example :

$var = "Some text Some text Some text <img src=\"test1.jpg\"/> Some text Some text Some text Some text <img src=\"test2.jpg\"/>";

I would like to change the two src for a value in a array :

$array = array("apple.jpg", "banana.jpg");

Then $var should look like :

"Some text Some text Some text <img src=\"apple.jpg\"/> Some text Some text Some text Some text <img src=\"banana.jpg\"/>"

I was doing a loop of every preg_match with src of img but i don't know how can i modify the src in the final var.

(Sorry for my english :( )

Thank.

EDIT :

Thank you very much for your answer

How can i do if then, i would to modify only src which begin by "data like : src="data etc

Upvotes: 2

Views: 1079

Answers (2)

rjdown
rjdown

Reputation: 9227

I would do something like this:

$var = "Some text Some text Some text <img src=\"test1.jpg\"/> Some text Some text Some text Some text <img src=\"test2.jpg\"/>";
$replacements = array("apple.jpg", "banana.jpg");
$search_pattern = '/(?<=src=").*?(?=")/';
preg_match_all($search_pattern, $var, $matches);
$var = str_replace($matches[0], $replacements, $var);

Upvotes: 2

Federkun
Federkun

Reputation: 36924

Another way to do it:

$var = "Some text Some text Some text <img src=\"test1.jpg\"/> Some text Some text Some text Some text <img src=\"test2.jpg\"/>";
$array = array("apple.jpg", "banana.jpg");

$var = preg_replace_callback('#<img.+?src="([^"]*)".*?/?>#i', function($m) use (&$array) {
    return str_replace($m[1], array_shift($array), $m[0]);
}, $var);

Upvotes: 6

Related Questions