RegexPHP-获取特定的文本,包括新行和多个空格



我试图获得从css开始的文本:{(some text…(}直到结束括号,而不是使用php将下面的文本包括在另一个文本文件中。

测试样本


just a sample text
css:{
"css/test.css",
"css/test2.css"
}
sample:text{
}

我使用vscode/supremesearch-and-replace工具来测试我的正则表达式语法,没有任何问题,我成功地获得了我想要的文本,包括里面的所有新行和空格,但当我试图将其应用于php时,我创建的正则表达式不起作用,它找不到我要查找的文本。

这是我的代码:

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!";
}

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

(css \s*\n*:\s**{\s*\n*(+(.|\s(|(.|\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

最新更新