0

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
  • That loop is very inefficient. Utilze preg_replace_callback and an array lookup. Commented Oct 11, 2011 at 6:48

1 Answer 1

3

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Will you need to escape the second example's { and } because they are surrounding an interpolated variable?
Ty, fixed. Not using embedded vars is nicer anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.