这将替换“MyClass”div 标记之间的所有文本并将新的 HTML 存储在 $string 中。
<?php
$string = '<div class="MyClass">Change this text.</div><br /><div class="MyClass">and this text too</div>';
$pattern = "|(?<=<div class=\"MyClass\">)(.*?)(?=<\/div>)|";
$replace = 'blah blah blah';
$matches = array();
preg_match_all($pattern, $string, $matches);
foreach ($matches[0] as $value) {
$string = str_replace($value, $replace, $string);
}
echo $string; // <div class="MyClass">blah blah blah</div><br /><div class="MyClass">blah blah blah</div>
?>
要替换包括 div 标签在内的所有内容,正则表达式模式将是$pattern = "|(<div class=\"MyClass\">.*?<\/div>)|";