我試圖用一個數組的新值替換數據屬性數據註釋。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。只需更換字符串就可以了,而不需要正則表達式 –