preg_replace:仅在大括号内删除注释

时间:2012-04-01 05:31:42

标签: php preg-replace

我有这个:

$text = 'This is some text /*Comment 1 */ . Some more text{ This is to let you know that /* this is a comment*/. A comment /*this one is */ can be anything }. So the next thing { This is to let you know that /*  this is a comment*/. A comment /*this one is */ can be anything } is another topic. /*Final comment*/';

需要这个:

$text = 'This is some text /*Comment 1 */ . Some more text{ This is to let you know that . A comment  can be anything }. So the next thing { This is to let you know that . A comment  can be anything } is another topic. /*Final comment*/';

试过这个:

$text = preg_replace("/\/\*.*?\*\//", "", $text);

问题在于我所尝试的是删除所有评论。我只想删除{ }中出现的评论。怎么做?

2 个答案:

答案 0 :(得分:2)

您可以使用以下正则表达式来标记字符串:

$tokens = preg_split('~(/\*.*?\*/|[{}])~s', $str, -1, PREG_SPLIT_DELIM_CAPTURE);

然后迭代标记以查找开头{及其中的注释:

$level = 0;
for ($i=1, $n=count($tokens); $i<$n; $i+=2) {  // iterate only the special tokens
    $token = &$tokens[$i];
    switch ($token) {
    case '{':
        $level++;
        break;
    case '}':
        if ($level < 1) {
            echo 'parse error: unexpected "}"';
            break 2;
       }
       $level--;
       break;
   default:  // since we only have four different tokens, this must be a comment
       if ($level > 0) {
           unset($tokens[$i]);
       }
       break;
   }
}
if ($level > 0) {
    echo 'parse error: expecting "}"';
} else {
    $str = implode('', $tokens);
}

答案 1 :(得分:0)

这可能是最安全的方式:

<?php

$text = 'This is some text /*Comment 1 */ . Some more text{ This is to let you know that /* this is a comment*/. A comment /*this one is */ can be anything }. So the next thing { This is to let you know that /*  this is a comment*/. A comment /*this one is */ can be anything } is another topic. /*Final comment*/';

$text = preg_replace_callback('#\{[^}]+\}#msi', 'remove_comments', $text);

var_dump($text);

function remove_comments($text) {
    return preg_replace('#/\*.*?\*/#msi', '', $text[0]);
}

?>

搜索{}然后删除其中的评论。这将删除{}中的多个评论。