我试图用一个数组的新值替换数据属性数据注释。preg_replace - 用新值替换数据属性?
$ids = array(
'111' => '999', // replace data-note=111 with data-note= 999
'222' => '888' // replace data-note=222 with data-note= 888
);
$html = '<span data-note="111" data-type="comment" name="a b c">el for 111 </span> text <span data-note="222" data-type="comment">el for 222 </span>';
foreach($ids as $oldKey => $newKey) {
$patterns[] = '/data-note="[' . $oldKey . ']/';
$replacements[] = '/data-note="[^"' . $newKey . ']"/';
}
echo preg_replace($patterns, $replacements, $html); // echos ... /data-note="[^"999]"/11" ...
我在做什么错?
什么是错的,你忘了写st错误 –
环替换你应该使用str_replace而不是preg_replace。只需更换字符串就可以了,而不需要正则表达式 –