Php 以非贪婪的方式使用匹配替换文本?

Php 以非贪婪的方式使用匹配替换文本?,php,xml,regex,preg-match,Php,Xml,Regex,Preg Match,我有一个SOAP调用,如下所示: <?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="urn:FileserveAPI" xmlns:types="urn:FileserveAPI

我有一个SOAP调用,如下所示:

<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="urn:FileserveAPI" xmlns:types="urn:FileserveAPI/encodedTypes" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><tns:login><username xsi:type="xsd:string">REPLACEME</username><password xsi:type="xsd:string">REPLACEMETOO</password></tns:login></soap:Body></soap:Envelope>
replacementplacemetoo
我想用定义的值替换REPLACEMEE和REPLACEMETOO,但在主题中,这些值可以是任何值

我试过这些赛前规则:

$body = preg_replace('#>.+?</username>#','>myuser</username>',$body);
$body = preg_replace('#>.+?</password>#','>mypw/username>',$body);
$body=preg#u replace(“#>.+?#”,“我的用户”,“$body”);
$body=preg_replace(“#>。+?#”,“>mypw/username>”,$body);
但我最终得到了这个字符串:

<?xml version="1.0" encoding="utf-8"?>myuser</username></tns:login></soap:Body></soap:Envelope>
myuser
我不明白为什么

为什么会发生这种情况?我需要如何修改我的规则

编辑:

我已经用一个否定字符类(如
[^>]+
解决了这个问题,但是我仍然对非贪婪不起作用的原因感兴趣。

试试:

$body = preg_replace("/(<username[^>]+>).+?(<\/username>)/", "$1new value$2", $input);
$body = preg_replace("/(<password[^>]+>).+?(<\/password>)/", "$1new value..$2", $input);
$body=preg_replace(“/(]+>).+?()/”,“$1新值$2”,$input);
$body=preg_replace(“/(]+>).+?()/”,“$1新值..$2”,$input);
这种“不贪心”的工作原理与预期一致

第一个正则表达式在遇到
时启动,然后只取最小值,直到到达第一个
为止

如果XML是:

<?xml version="1.0"><accnt1><username>foo</username></accnt1><accnt2><username>bar</username></accnt2> ...
foobar。。。

然后,
.+?
抓取:

><accnt1><username>foo</username>
>foo

然而,
.+
会抓住:

><accnt1><username>foo</username></accnt1><accnt2><username>bar</username>
foobar
谢谢,我已经有了一个使用否定字符类[^>]的快速修复方法,但是你的工作很好,看起来也不错。我仍然很好奇为什么非贪婪不起作用,尽管您知道格式良好的XML可以在开始和结束标记中包含空格吗?那么,除了这些文档是有效的XML之外,您还要对这些文档的发送者施加约束?在没有适当的XML解析器的情况下处理XML是错误的。它也可能非常低效。好吧,这是有道理的!如果我理解正确的话,我可以把y贪婪的火柴放在前面来补偿——在这种情况下——不受欢迎的行为,对吗?是的,如果你小心的话。最好使用
[^>]+
类型方法。