以非贪婪的方式使用匹配替换文本?
我有一个 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>
我想用定义的值替换 REPLACEMEE 和 REPLACEMETOO,但在主题中这些值可以是任何值。
我尝试了这些 preg_match 规则:
$body = preg_replace('#>.+?</username>#','>myuser</username>',$body);
$body = preg_replace('#>.+?</password>#','>mypw/username>',$body);
但我最终得到了这个字符串:
<?xml version="1.0" encoding="utf-8"?>myuser</username></tns:login></soap:Body></soap:Envelope>
我不明白为什么?
为什么会发生这种情况?我需要如何修改我的规则?
编辑:
我已经用诸如 [^>]+
这样的否定字符类解决了这个问题,但是我仍然对为什么非贪婪不起作用感兴趣。
I have a SOAP Call that looks like this:
<?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>
I want to replace REPLACEMEE and REPLACEMETOO with defined values, but in the subject those values can be anything.
I tried theese preg_match rules:
$body = preg_replace('#>.+?</username>#','>myuser</username>',$body);
$body = preg_replace('#>.+?</password>#','>mypw/username>',$body);
But I end up with this string:
<?xml version="1.0" encoding="utf-8"?>myuser</username></tns:login></soap:Body></soap:Envelope>
I cant understand why?
Why is this occouring and how do I need to modify my rules?
Edit:
I already worked my way around it with a negated character class like [^>]+
however I am still intersted in why the non greedyness doesnt work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
“非贪婪”按预期工作。
第一个正则表达式在遇到
>
时启动,然后仅采用最小值,直到到达第一个。
如果 XML 是:
然后
>.+?
抓取:而
>.+
会抓取:The "non greedyness" works as expected.
The first regex started when it encountered
>
and then took only the minimum until the first</username>
was reached.If the XML had been:
Then
>.+?</username>
grabs:Whereas
>.+</username>
would grab:尝试:
Try: