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

Tags: , , , ,

I was trying to get the text starting from css:{(some text…)} up to the ending bracket only, not including the texts below in another text file using php.


just a sample text






I’m using vscode/sublime search and replace tool to test my regex syntax and nothing is wrong, I successfully get the text that I want including all the new lines and spaces inside, but when i tried to apply it on php, the regex that I created doesn’t work, it cannot find the text that im looking for.

here is my code:


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

This is my regex that I just created.


Please help me, Im open for any suggestion, Im a newbie on regular expression, Im lacking on knowledge about the logic of it.



Hey guys I found the solution! base on the answer of @alex

Dont really know if I am implementing this right.

Here is my code

$src = "src/page/"; //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;

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

      fclose($file);//close the file

Source: stackoverflow