Preg使用php替换图像类

时间:2014-01-09 14:08:26

标签: php preg-replace

我有一个类'attachment-fullslideshow'的图像。代码是

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

我想将“attachment-fullslideshow”中的类替换为“attachment-fullslideshow quote”。

请建议。

2 个答案:

答案 0 :(得分:3)

你可以这样做:

$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>

或使用正则表达式:

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

希望这有帮助!

答案 1 :(得分:1)

你也可以

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

输出

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