php preg_replace not doing anything

空扰寡人 提交于 2020-05-09 17:22:30

问题


For some reason my preg_replace call is not working, I have check everything I can think of to no avail. Any suggestions?

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

vars is an array containing the $key->value that needs to be replaced in the string, tempContentXML is a string containing XML data.

Piece of the string

...<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);
}

That should replace the string {Reference} with the value in the array at $key

But it is not working.


回答1:


The replacement does not happen in-place (the new string returned).

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

Besides that, don't use a regex for plain string replacements ever (assuming $this->vars does not contain regexes):

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


来源:https://stackoverflow.com/questions/7722222/php-preg-replace-not-doing-anything

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!