sim*_*mes 3 css php regex arrays
我正在尝试编写一些PHP来读取CSS文件,查找所有@group注释及其行号.这是我到目前为止所做的,但它返回字符数而不是行号.
$file = 'master.css';
$string = file_get_contents($file);
$matches = array();
preg_match_all('/\/\* @group.*?\*\//m', $string, $matches, PREG_OFFSET_CAPTURE);
list($capture, $offset) = $matches[0];
$line_number = substr_count(substr($string, 0, $offset), "\n") + 1;
echo '<pre>';
print_r($matches[0]);
echo '</pre>';
Run Code Online (Sandbox Code Playgroud)
尝试使用file()而不是file_get_contents().区别在于file()将文件内容作为数组返回,每行返回一个元素,而不是像do那样返回字符串file_get_contents.我应该注意,file()返回每行末尾的换行符作为数组元素的一部分.如果您不想这样,请将FILE_IGNORE_NEW_LINES标志添加为第二个参数.
从那里,您可以使用preg_grep()仅返回初始数组中的元素.如果只需要行号,您可以读取它们的索引以确定匹配的行:
一个例子:
myfile.txt文件:
hello world
how are you
say hello back!
Run Code Online (Sandbox Code Playgroud)
line_find.php:
$filename = "myfile.txt";
$fileContents = file($filename);
$pattern = "/hello/";
$linesFound = preg_grep($pattern, $fileContents);
echo "<pre>", print_r($linesFound, true), "</pre>";
Run Code Online (Sandbox Code Playgroud)
结果:
Array
(
[0] => hello world
[2] => say hello back!
)
Run Code Online (Sandbox Code Playgroud)
希望有所帮助.