2014-04-04 58 views
0

我試圖用一個數組的新值替換數據屬性數據註釋。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" ... 

我在做什麼錯?

+0

什麼是錯的,你忘了寫st錯誤 –

+0

環替換你應該使用str_replace而不是preg_replace。只需更換字符串就可以了,而不需要正則表達式 –

回答

2

[]是特殊車型字符的正則表達式,你必須轉義:

$patterns[] = '/data-note="\[' . $oldKey . '\]/'; 

而且我猜你想簡單地說:

$patterns[] = '/data-note="' . $oldKey . '"/'; 

變化還更換部分:

$replacements[] = 'data-note="' . $newKey . '"'; 
+0

感謝您的答案,但不幸的是,這兩個模式都會返回原始字符串而不會發生任何更改。 – Cris

+0

@Cris:你的預期結果是什麼?第二個適用於我,除非你想要另外一個' Toto

+0

最終結果應該是 Cris