2014-04-04 60 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