2012-04-01 58 views
0

我有這樣的:的preg_replace:只在花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); 

問題是,我試過的,是刪除所有的評論。我只想將{ }內的評論刪除。這個怎麼做?

+0

如果你有像' {/ *} * /}'? – Gumbo 2012-04-01 05:40:02

+0

沒有想到它。這種數據是意想不到的。在這種情況下可能的解決方案是什麼? – Devner 2012-04-01 06:44:08

+0

這一切都取決於你。但是在定義這種語言時應該考慮這種情況。 – Gumbo 2012-04-01 06:47:28

回答

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

?> 

。這將刪除{}中的多條評論。

+0

非常感謝!完美的作品! – Devner 2012-04-01 06:46:51

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

+1因爲即使這是一個工作解決方案。你對這種工作方式的理解程度遠遠超過我。而且因爲我無法接受2個職位作爲答案,所以我對此進行了投票。 – Devner 2012-04-01 06:49:11