php捕获组 [英] php capture group

查看:40
本文介绍了php捕获组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 php 中使用 preg_match() 捕获一个组有点卡住了.

I'm kind of stuck capturing a group with preg_match() in php.

这是我的模式:

<ns2:uniqueIds>(.*)<\/ns2:uniqueIds>

这是来源:

<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope"><env:Header/><env:Body><ns2:ListResponse xmlns:ns2="http://censored"><ns2:uniqueIds>censored</ns2:uniqueIds><ns2:uniqueIds>censored</ns2:uniqueIds></ns2:ListResponse></env:Body></env:Envelope>

我错过了什么?

推荐答案

虽然我同意上面的人告诉你不要使用正则表达式来解析 XML,但我明白你为什么这样做只是为了获取一些价值.这就是我设法让它工作的方式:

While I agree with the people above that tell you to not use regular expressions to parse XML, I can see why you are doing it to just grab some value. This is how I managed to make it work:

PHP 解释器示例:

php > $s = '<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope"><env:Header/><env:Body><ns2:ListResponse xmlns:ns2="http://censored"><ns2:uniqueIds>censored</ns2:uniqueIds><ns2:uniqueIds>censored</ns2:uniqueIds></ns2:ListResponse></env:Body></env:Envelope>';
php > $p = '#<ns2:uniqueIds>(.*?)<\/ns2:uniqueIds>#i';
php > $a = array();
php > preg_match($p, $s, $a);
php > print_r($a);
Array
(
    [0] => <ns2:uniqueIds>censored</ns2:uniqueIds>
    [1] => censored
)

我对您的模式所做的唯一更改是我使用了惰性量词 *?而不仅仅是 * (这是贪婪的).

The only changes that I've made to your pattern is that I've used the lazy quantifier *? instead of just * (which is greedy).

来源:

这篇关于php捕获组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆