Using regex with XML
I'm trying to use regular expressions to extract the CDATA from the following XML feed: http://www.patrickarundell.net/THREE-IE-FEED.asp
My code is as follows:
$xml = file_get_contents('http://www.patrickarundell.net/THREE-IE-FEED.asp');
$arr = array();
preg_match('/(CDATA)(.*)/', $xml, $arr);
echo '<pre>';
print_r($arr);
echo '</pre>';
The output is:
Array
(
[0] => CDATA[
[1] => CDATA
[2] => [
)
I know I don't have the regular expression quite right, but when I try the following statement:
preg_match('/(<![CDATA[)(.*)/', $xml, $arr);
I get开发者_开发知识库 an error:
Warning: preg_match() [function.preg-match]: Compilation failed: missing terminating ] for character class at offset 15
I thought this might give me the details after the square bracket '[', which is what I'm looking for.
Any help appreciated, I've been trying this for a few hours and having no luck.
The reason for the error message is that it is missing a closing ]
for a character class. But you didn't want to define a character class with your [
you want to match it, so you nedd to escape it \[
.
<!\[(CDATA)\[\s*(.*?)\s*\]\]>
I tested it here on regexr
The .*?
is a non greedy match, it matches as less as possible, until it finds the closing ]]>
.
精彩评论