1

I would like to be able to parse the following data using PHP:

$string = "<![CDATA[<div><b>Color:</b> Blue</div>
<div><b>Number:</b> 5</div>
<div><b>Month:</b> January</div>]]>";

Into an array such as:

Array
(
    [Color] = Blue
    [Number] = 5
    [Month] = January
)

I attempted to use preg_match to extract the data between , however, it would not produce any matches.

preg_match_all("/\[CDATA\[(.*?)\]]/", $string, $result);

I can't get past this point. Any help would be appreciated.

1
  • Two things, why the (.*?) has a ?. and why haven't you escaped ] in \]]? Commented Apr 12, 2012 at 22:20

1 Answer 1

1
$result=array();
$arr = explode("\n", strip_tags(substr($string,9, strlen($string)-12)));
foreach($arr as $val){
    $tmp = explode(':',$val);
    $result[$tmp[0]] = $tmp[1];
}

(Add checks, trims, code style and so on yourself)

Sign up to request clarification or add additional context in comments.

2 Comments

You'd probably want to remove the <![CDATA[ prior to running strip_tags() but other than that this would seem to be a good answer.
@Spudley thats why there is substr()

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.