2011-10-11 133 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