How can I extract a string enclosed in CDATA tag using php? For instance I have
$str = "<![CDATA[this is my text]]>";
Using regex how can I extract the string "this is my text"?
You can use this regex: /<!\[CDATA\[(.*?)\]\]>/
:
$str = "<![CDATA[this is my text]]>";
$matches = array();
preg_match('/<!\[CDATA\[(.*?)\]\]>/', $str, $matches);
echo $matches[1]; // this is my text
The regex looks for <![CDATA[
followed by any characters until the first ]]>
is encountered.
if your string always starts with <![CDATA[
and ends with ]]>
you can use substr()
$str = "<![CDATA[this is my text]]>";
$output = substr($str,9,strlen($str)-12);
echo $output;