正则表达式 PHP - 获取包含新行和多个空格的特定文本

Regex PHP - Get specific text including new lines and multiple spaces

我试图获取从 css:{(some text...)} 开始到结尾括号的文本,不包括文本下面在另一个文本文件中使用 php.

test.sample


just a sample text

css:{

 "css/test.css",
    "css/test2.css"

}

sample:text{

}

我正在使用 vscode/sublime 搜索和替换 工具来测试我的正则表达式语法,没有任何问题,我成功了获取我想要的文本,包括里面的所有新行和空格,但是当我尝试将它应用于 php 时,我创建的正则表达式不起作用,它找不到我要查找的文本。

这是我的代码:

myphp.php

$file = file_get_contents("src/page/test.sample");
echo $file . "<br>";
if (preg_match_all("/(css\s*\n*:\s*\n*\{\s*\n*)+((.|\n\S)*|(.|\n\s)*)(\n*)(\}\W)$/", $file)) {
    echo "Success";
} else {
    echo "Failed!";
}

这是我刚刚创建的正则表达式。

(css\s*\n*:\s*\n*{\s*\n*)+((.|\n\S)|(.|\n\s))(\n*)(}\W)$

请帮助我,我愿意接受任何建议,我是正则表达式的新手,我对它的逻辑缺乏了解。

谢谢。

试试这个我的朋友:

<?php

$file = "testfile.php"; // call the file

$f = fopen($file, 'rb'); // open the file

$found = false;

while ($line = fgets($f, 1000)) { // read every line of the file

    if ($found) {

       echo $line;

       continue;

    }

    if (strpos($line, "css:") !== FALSE) { // if we found the word 'css:' we print everything after that

      $found = true;

    }

}

大家好,我找到了解决方案!基于@alex

的回答

Dont really know if I am implementing this right.

这是我的代码

$src = "src/page/darwin.al"; //get the source file
      $file = fopen($src,"rb"); //I dont really know what 'rb' means, I guess it simply means, 'not a commong text file'?, search for it!
      $found = false;
      $css = false;
      while($line = fgets($file)){ //read every line of text and assign that line of text in a variable $line

            if(strpos(preg_replace("/\s*/", "", $line), "css:{") === 0){ //if the current line is == 'css:{' <the thing that Im looking for,
                $found = true;
                $css = true;
            }elseif($css && strpos(preg_replace("/\s*/", "", $line),"}") === 0){ //If we are still inside the css block and found the '{'
                echo $line;
                break;
            }

            if ($found) {
                echo preg_replace("/\s*/", "", $line); //remove every whitespace!
            }

      }
      fclose($file);//close the file