问题
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