duanhegn231318
duanhegn231318
2012-06-13 05:42

如何使用正则表达式提取CDATA之间的字符串部分?

已采纳

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"?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • dowm41315 dowm41315 9年前

    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.

    点赞 评论 复制链接分享
  • doujuyang1764 doujuyang1764 9年前

    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;
    
    点赞 评论 复制链接分享

相关推荐