Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 248
  • Last Modified:

Regular Expression for xml extraction

I have XML files of the following form:

<a>
.
.
.
<b>
<c>variable-length multi-line markup</c>
<c>variable-length multi-line markup</c>
<c>variable-length multi-line markup</c>
.
.
.
<c>variable-length multi-line markup</c>
</b>
.
.
.
</a>

I'm trying to find the easiest way to extract the c elements into an array. I tried using

preg_match_all("'(\<c\>)[\s\S]*(\<\/c\>)'",$xml,$matches);

but $matches[0][0] just grabs everything between the first <c> and the last </c>. I'm wondering if there is some expression I could use to limit the matches to individual sets of <c>...</c>, or if some other method might work.

Thanks.
0
huenterprises
Asked:
huenterprises
1 Solution
 
bobsledbobCommented:

preg_match_all("'(\<c\>)[\s\S]*?(\<\/c\>)'",$xml,$matches);

The addition of the question mark there means "don't be greedy".  Basically, you were matching the first <c> and the very last </c>.  Telling it not to be greedy tries to minimize the matching, rather than maximizing.

By the way, doesn't this work too (and it's a bit shorter).  Do you really need to paranthesize the <c>'s??

preg_match_all("|<c>[\s\S]*?</c>|", $xml, $matches);

More info about greedy at the PHP manual page...

http://www.php.net/manual/en/function.preg-match-all.php

0
 
snoyes_jwCommented:
You might also try using PHP's XML parser
(http://www.php.net/manual/en/ref.xml.php)

You can specify in your open/close tag handler functions to set/unset some flag when you reach tag "c", then test for that flag in your character data handler function to add the contents to an array.
0
 
huenterprisesAuthor Commented:
Thanks.

preg_match_all("|<c>[\s\S]*?</c>|", $xml, $matches);

That was just what I was needing.
0
 
jayrodCommented:
where is the best place to learn about preg_match syntax?
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now