繁体   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