php 如何删除`//<![CDATA[` 并结束`//]]>`?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8283588/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove `//<![CDATA[` and end `//]]>`?
提问by bomanden
How can I remove the (//<![CDATA[ , //]]>
) blocks; tags inside a script
element.
如何删除(//<![CDATA[ , //]]>
) 块;script
元素内的标签。
<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.
看起来可以完成,preg_replace()
但还没有找到适合我的解决方案。
What regex would I use?
我会使用什么正则表达式?
采纳答案by alex
回答by Dimme
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);
回答by Alan Moore
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.
这将删除包含每个标签的整行,而不会弄乱所附代码的缩进。
回答by Rohan Kumar
You can also try,
你也可以试试,
$s=str_replace(array("//<![CDATA[","//]]>"),"",$s);
回答by Fathur Rohim
I use like this to remove <![CDATA[]]
but on single line now work for me, dont know if for multiple line string.
我用这样的方式删除,<![CDATA[]]
但现在单行对我有用,不知道是否适用于多行字符串。
preg_match_all('/CDATA\[(.*?)\]/', $your_string_before_this, $datas);
$string_result_after_this = $datas[1][0];
回答by duttyman
$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));
}
回答by pulzarraider
If <![CDATA[
contains some html special character, e.g. &
, "
, '
, <
, >
and you will work with the rest of the string as it is still XML, you should escape those chars.
Otherwise you will make your XML invalid.
如果<![CDATA[
包含一些 html 特殊字符,例如&
, "
, '
, <
,>
并且您将使用字符串的其余部分,因为它仍然是 XML,您应该转义这些字符。否则,您将使您的 XML 无效。
function removeCDataFromString(string $string)
{
return preg_replace_callback(
'~<!\[CDATA\[(.*)\]\]>~',
function (array $matches) {
return htmlspecialchars($matches[1], ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
},
$string
);
}
回答by Siddharth
use str_replace()
instead of preg_replace()
it's lot easier
使用str_replace()
而不是preg_replace()
更容易
$var = str_replace('<![CDATA[', '', $var);
$var = str_replace(']]','',$var);
echo $var;