views:

47

answers:

2

Hi,

Im 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"&gt;&lt;env:Header/&gt;&lt;env:Body&gt;&lt;ns2:ListResponse xmlns:ns2="http://censored"&gt;&lt;ns2:uniqueIds&gt;censored&lt;/ns2:uniqueIds&gt;&lt;ns2:uniqueIds&gt;censored&lt;/ns2:uniqueIds&gt;&lt;/ns2:ListResponse&gt;&lt;/env:Body&gt;&lt;/env:Envelope&gt;

What am i missing?

A: 

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.

PatrikAkerstrand
Because it doesn't work. There is a problem with the server and I dont have access to it. Can you please tell me what i'm doing wrong?
Yustme
+2  A: 

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"&gt;&lt;env:Header/&gt;&lt;env:Body&gt;&lt;ns2:ListResponse xmlns:ns2="http://censored"&gt;&lt;ns2:uniqueIds&gt;censored&lt;/ns2:uniqueIds&gt;&lt;ns2:uniqueIds&gt;censored&lt;/ns2:uniqueIds&gt;&lt;/ns2:ListResponse&gt;&lt;/env:Body&gt;&lt;/env:Envelope&gt;';
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:

André Laszlo
And i agree with them. But like i said, all other options failed me. But if anyone can parse that xml string and get the value of the tag name 'value', I'd be happy to use that instead.
Yustme
No worksy?Oh, and you should use preg_match_all if you're interested in more than one of your uniqueIds.
André Laszlo
How come you accepted my answer and then... unaccepted it? Something not working?
André Laszlo