2011-10-11 129 views
0

由於某種原因,我的preg_replace調用不起作用,我已經檢查了一切我能想到的無濟於事。有什麼建議麼?php preg_replace沒有做任何事情

foreach ($this->vars as $key=>$var) 
{ 
    preg_replace("/\{$key\}/", $var, $this->tempContentXML); 
} 

瓦爾是包含$鍵 - >值,該值需要在字符串中被替換的陣列,tempContentXML是包含XML數據的字符串。

一塊串

...<table:table-cell table:style-name="Table3.B1" office:value-type="string"><text:p text:style-name="P9">{Reference}</text:p></table:table-cell></table:table-row><table:table-row table:style-name="Table3.1"><... 

EX的。

$this->vars['Reference'] = Test; 
foreach ($this->vars as $key=>$var) 
{ 
    preg_replace("/\{$key\}/", $var, $this->tempContentXML); 
} 

應該替換字符串引用衝與數組中的價值在$關鍵

但它無法正常工作。

+0

這個循環是非常低效的。使用preg_replace_callback和數組查找。 – mario

回答

3

替換不會在原地發生(返回的新字符串)。

foreach ($this->vars as $key=>$var) { 
    $this->tempContentXML = preg_replace("/\{$key\}/", $var, $this->tempContentXML); 
} 

除此之外,不使用正則表達式爲普通字符串替換過(假設$this->vars不包含正則表達式):

foreach ($this->vars as $key=>$var) { 
    $this->tempContentXML = str_replace('{'.$key.'}', $var, $this->tempContentXML); 
} 
+2

您是否需要轉義第二個示例的「{」和「}」,因爲它們圍繞着插值變量? – alex

+0

Ty,固定。無論如何,不​​使用嵌入式變量更好。 – ThiefMaster