preg_replace:只删除卷曲背景中的注释


preg_replace: Remove comments only within curly backets

我有这个:

$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);

问题是,我所尝试的是删除所有的评论。我只想删除{ }中出现的注释。如何做到这一点?

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

$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);
}

这可能是最安全的方法:

<?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]);
}
?>

它搜索{},然后删除其中的注释。这将删除{}中的多个注释。