开发者

PHP - get line number of regex result

开发者 https://www.devze.com 2023-02-19 14:56 出处:网络
I\'m trying to write some PHP that will read a CSS file, find all occurrences of the @group comment, and their line number. This is what I have so far, but it\'s returning the character count rather t

I'm trying to write some PHP that will read a CSS file, find all occurrences of the @group comment, and their line number. This is what I have so far, but it's returning the character count rather than the line number.

$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>';


Try using file() rather than file_get_contents(). The difference is that file() returns the file contents as an array, one element per line, rather than as a string like file_get_contents does. I should note that file() returns the newline character at the end of each line as part of the array element. If you don't want that, add the FILE_IGNORE_NEW_LINES flag as a second parameter.

From there, you can use preg_grep() to return only the elements in the initial array. You can read their indexes to determine which lines matched, if you only want the line numbers:

An example:

myfile.txt:

hello world
how are you
say hello back!

line_find.php:

$filename = "myfile.txt";
$fileContents = file($filename);

$pattern = "/hello/";
$linesFound = preg_grep($pattern, $fileContents);

echo "<pre>", print_r($linesFound, true), "</pre>";

Result:

Array
(
    [0] => hello world

    [2] => say hello back!
)

Hope that helps.


This is not going to be optimal, but if you don't care about that :

$line_number = 1 + substr_count($string, "\n", 0, $index);

It's just counting the number of new line characters found up until that index you get from the offset capture.

0

精彩评论

暂无评论...
验证码 换一张
取 消