How to remove `//<![CDATA[` and end `//]]>`?

2019-04-20 09:05发布

How can I remove the (//<![CDATA[ , //]]>) blocks; tags inside a script element.

<script type="text/javascript">
    //<![CDATA[
    var l=new Array();
    ..........................
    ..........................
    //]]>
</script>

Looks like it can be done with preg_replace() but havent found a solution that works for me.

What regex would I use?

7条回答
Anthone
2楼-- · 2019-04-20 09:38

use str_replace() instead of preg_replace() it's lot easier

$var = str_replace('<![CDATA[', '', $var);
$var = str_replace(']]','',$var);
echo $var;
查看更多
ら.Afraid
3楼-- · 2019-04-20 09:38

I use like this to remove <![CDATA[]] but on single line now work for me, dont know if for multiple line string.

preg_match_all('/CDATA\[(.*?)\]/', $your_string_before_this, $datas); 
$string_result_after_this = $datas[1][0];
查看更多
男人必须洒脱
4楼-- · 2019-04-20 09:43

If you must...

$s = preg_replace('~//<!\[CDATA\[\s*|\s*//\]\]>~', '', $s);

This will remove the whole line containing each tag without messing up the indentation of the enclosed code.

查看更多
等我变得足够好
5楼-- · 2019-04-20 09:43

You can also try,

$s=str_replace(array("//<![CDATA[","//]]>"),"",$s);
查看更多
beautiful°
6楼-- · 2019-04-20 09:45
$nodeText = '<![CDATA[some text]]>';
$text = removeCdataFormat($nodeText);    

public function removeCdataFormat($nodeText)
{
    $regex_replace = array('','');
    $regex_patterns = array(
        '/<!\[CDATA\[/',
        '/\]\]>/'
   );
   return trim(preg_replace($regex_patterns, $regex_replace, $nodeText));
}
查看更多
Emotional °昔
7楼-- · 2019-04-20 09:54

You don't need regex for a static string.

Replace those parts of the texts with nothing:

$string = str_replace("//<![CDATA[","",$string);
$string = str_replace("//]]>","",$string);
查看更多
登录 后发表回答