簡體   English   中英

從json文件中刪除假評論

[英]remove fake comments from json file

由於json不支持評論,因此我需要自己的函數來清理評論。我的評論是CSS樣式,例如

/*comment*/

我嘗試了以下

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

但沒有運氣。 謝謝

echo preg_replace("#/\*.*?\*/#s", "", $json);

顯着變化:

  • 我使用#作為模式定界符。 這樣,我就不需要轉義正斜杠,從而使正則表達式更易於閱讀。
  • 我添加了s標志,使成為. 還匹配換行符。

當心,這將破壞json字符串中的注釋。 一個例子的json對象將變得更加混亂

{"codeSample": " /*******THIS WILL GET STRIPPED OUT******/"}

使用以下內容:

$json = preg_replace('!/\*.*?\*/!s', '', $json); // remove comments
$json = preg_replace('/\n\s*\n/', "\n", $json); // remove empty lines that can create errors

這將刪除注釋,多行注釋和空行

編輯:正如某些人在評論中所說,您可以使用:

 $json = preg_replace('/\s*(?!<\")\/\*[^\*]+\*\/(?!\")\s*/', '', $json);

僅刪除在字符串中找不到的注釋。

$string = "some text /*comment goes here*/ some text again /*some comment again*/";
$string = preg_replace( '/\s*(?!<\")\/\*[^\*]+\*\/(?!\")\s*/' , '' , $string );
echo $string; // some textsome text again

完整的php代碼可刪除單行和多行注釋。

$json = preg_replace('!/\*.*?\*/!s', '', $json); //Strip multi-line comments: '/* comment */'
$json = preg_replace('!//.*!', '', $json);       //Strip single-line comments: '// comment'
$json = preg_replace('/\n\s*\n/', "\n", $json);  //Remove empty-lines (as clean up for above)

您可以在此處測試代碼的網站: https : //www.phpliveregex.com

要測試第一行代碼,請如下圖所示:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM