0

I've been using regular expressions to target text between XML elements and it works fine with most elements in the XML tree. However, the elements that are clickable/expandable when viewing the raw XML document in the web browser don't get targeted by regex. When I use preg_match in PHP I just get an empty array.

Now, I know works but just to be clear, here it is:

$contents "random fetched xml doc";
$regex = '/<element>(.*?)<\/element>/';
preg_match_all($regex, $contents, $output);

print_r($output);

Please note: I have googled the issue and found a lot of results saying you shouldn't parse XML with regex. I am not interested in learning how to parse XML in general, I'm learning a technique for scraping data from websites, and I'm just practicing on a website containing XML pages, since they provide intuitive delimiters (the XML tags).

My question is simply: How do I modify my regex to target the expandable XML elements?

EDIT: SOLVED ISSUE The question was based on false premises. The problem has nothing to do with XML, but rather that my regular expression matched anything between the elements except linebreaks. After adding /s at the end of my expression, it works like a charm. Thanks for your time!

6
  • 1
    Use some XML parser. There plenty of them search.cpan.org/search?query=xml+parser&mode=all
    – alex
    Dec 18, 2012 at 21:42
  • And search.cpan.org/~shlomif/XML-LibXML-2.0014/LibXML.pod as well. Regex usually used for different needs.
    – alex
    Dec 18, 2012 at 21:44
  • It would probably help if you provided a short example and noted which elements your current approach works for an which it doesn't work for. The phrase "the elements that are clickable/expandable ... in the web browser" means nothing to at least this reader (browser behavior is not specified by the XML spec, and in all the browsers I know, if any elements are expandable all are). Impossible to tell what's going wrong without more information. Dec 18, 2012 at 22:01
  • Yeah, but I don't know how to use them and I would much rather just find out how I can modify my code above.
    – user1781186
    Dec 18, 2012 at 22:02
  • You could possibly add that as an answer, to don't leave this unanswered. :P Dec 18, 2012 at 23:46

1 Answer 1

0

I figured it out after a while. The question was based on false premises. The problem has nothing to do with XML, but rather that my regular expression matched anything between the elements except linebreaks. After adding /s at the end of my expression, it works like a charm. Thanks for your time!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.