php preg_replace 不执行任何操作

发布于 2024-12-09 04:38:54 字数 821 浏览 12 评论 0原文

由于某种原因,我的 preg_replace 调用不起作用,我已经检查了我能想到的所有内容,但无济于事。有什么建议吗?

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

vars 是一个数组,其中包含字符串中需要替换的 $key->value,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);
}

这应该用 $key 处数组中的值替换字符串 {Reference}

但它不起作用。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

只是一片海 2024-12-16 04:38:54

替换不会就地发生(返回新字符串)。

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

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);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文