簡體   English   中英

正則表達式 PHP - 獲取特定文本,包括換行符和多個空格

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

我試圖獲取從css:{(some text...)}開始的文本直到結束括號,不包括使用 php 的另一個文本文件中的以下文本。

測試樣本


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的回答

真的不知道我是否正在實施這項權利。

這是我的代碼

$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

暫無
暫無

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

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