卸下支架但保持CDATA不变

时间:2012-09-09 12:18:09

标签: php cdata

是否可以移除内部的支架但保持CDATA标签不变?怎么样?

<![CDATA[

This is some Text with [brackets inside]

]]>

编辑:我使用PHP,抱歉。

编辑II:我看到我可以使用外观断言,但有点不知道如何做开启括号可能在CDATA之前或之后以及如何连接最后两个块的AND连接器。

2 个答案:

答案 0 :(得分:2)

这是你需要的正则表达式:

$subject = 'your_input_text';
$matchPattern = '/(<!\[CDATA\[[^[]*)\[(.*?)\]([^\]]*\]\]>)/s';
$replacePattern = '$1$2$3';
$result = preg_replace($matchPattern, $replacePattern, $subject);

您可以看到结果 here

以下是正则表达式的解释:

# (<!\[CDATA\[[^\[]*)\[(.*?)\]([^\]]*\]\]>)
# 
# Options: dot matches newline
# 
# Match the regular expression below and capture its match into backreference number 1 «(<!\[CDATA\[[^\[]*)»
#    Match the characters “<!” literally «<!»
#    Match the character “[” literally «\[»
#    Match the characters “CDATA” literally «CDATA»
#    Match the character “[” literally «\[»
#    Match any character that is NOT a [ character «[^\[]*»
#       Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
# Match the character “[” literally «\[»
# Match the regular expression below and capture its match into backreference number 2 «(.*?)»
#    Match any single character «.*?»
#       Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
# Match the character “]” literally «\]»
# Match the regular expression below and capture its match into backreference number 3 «([^\]]*\]\]>)»
#    Match any character that is NOT a ] character «[^\]]*»
#       Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
#    Match the character “]” literally «\]»
#    Match the character “]” literally «\]»
#    Match the character “>” literally «>»

答案 1 :(得分:1)

// uses MFC CString syntax but any string library will have the same essential functions

CString myCDATA;
CString workString;
int iTagStart;

iTagStart = String.Find("<![CDATA[") + 9 // 9 = length of "<![CDATA["
// get the string without the endpoints
workString = CString.Mid(iTagStart,myCDATA.GetLength() - 9 - 3); // 3 = length of "]]>"
workString.Replace("[","");
workString.Replace("]","");
// reassemble
myCDATA = "<![CDATA[" + workString + "]]>";
相关问题