Prithviraj Mitra
Prithviraj Mitra

Reputation: 11812

Preg replace image class using php

I have a image with class 'attachment-fullslideshow'. The code is

<img class="attachment-fullslideshow" src="demo.jpg">

I would like to replace the class from 'attachment-fullslideshow' to 'attachment-fullslideshow quote'.

Please suggest.

Upvotes: 0

Views: 1124

Answers (2)

davidkonrad
davidkonrad

Reputation: 85528

You could also

$html = '<img class="attachment-fullslideshow" src="demo.jpg">';
$test = preg_replace('/class="(.*?)"/s', 'class="newclass"', $html);
echo $test;

outputs

<img class="newclass" src="demo.jpg">

Upvotes: 1

Victor York
Victor York

Reputation: 1681

You could do something like this:

$str = '<img class="attachment-fullslideshow" src="demo.jpg">';

$str = str_replace('class="attachment-fullslideshow', 'class="attachment-fullslideshow quote', $str);

//Result: <div class="attachment-fullslideshow quote">...</div>

Or with regular expressions:

$str = '<img class="attachment-fullslideshow" src="demo.jpg">';
$str = preg_replace(':class="(.*attachment-fullslideshow.*)":', 'class="\1 quote"', $str);
//Result: <div class="defaultClass myClass">...</div>

Hope this helps!

Upvotes: 2

Related Questions