0

是否可以删除里面的括号但保持 CDATA 标签不变?如何?

<![CDATA[

This is some Text with [brackets inside]

]]>

编辑:我使用 PHP,对不起。

编辑二:我看到我可以使用环视断言,但有点不知道如何做 AND 连接器,即左括号可能在 CDATA 之前或之后,以及如何连接最后两个块。

4

2 回答 2

2

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

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

你可以在这里看到结果。

这是正则表达式模式的解释:

# (<!\[CDATA\[[^\[]*)\[(.*?)\]([^\]]*\]\]>)
# 
# Options: dot matches newline
# 
# Match the regular expression below and capture its match into backreference number 1 «(<!\[CDATA\[[^\[]*)»
#    Match the characters “&lt;!” 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 “&gt;” literally «>»
于 2012-09-09T13:15:32.457 回答
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 + "]]>";
于 2012-09-09T12:27:35.840 回答