Skip to content
Advertisement

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

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.

test.sample

just a sample text

css:{

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

}

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:

myphp.php

$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.

(csss*n*:s*n*{s*n*)+((.|nS)|(.|ns))(n*)(}W)$

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

thanks.

Advertisement

Answer

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/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
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement