php capture group

六眼飞鱼酱① 提交于 2019-12-13 18:42:09

问题


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

This is my pattern:

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

And this is the source:

<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>

What am I missing?


回答1:


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 interpreter example:

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).

Sources:

  • About the lazy repetition stuff: http://www.php.net/manual/en/regexp.reference.repetition.php



回答2:


You should probably use the native SoapClient instead to make it easier to both invoke the WebService as well as get the result as a PHP native datatype..

Using regular expressions to parse XML or HTML is usually a (very) bad idea.



来源:https://stackoverflow.com/questions/3386562/php-capture-group

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!