开发者

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜