I am writing a PHP program which reads file with file_get_contents then attempts to count effective lines in that source file. It must not count empty lines or lines containing comments only. Sample file:
<?php
/**
* blah blah
*/
class Test {
// testfunc
function testfunc(){
return;
}
}
The number of lines in such a file should be 5. Here is what I’ve got so far:
$f=file_get_contents($this->file);
$f=preg_replace('|/\*.*?\*/|s','',$f);
$f=preg_replace('/^\s*$/','',$f); // <-- does not work
$f=preg_replace("/\n\n*/s","\n",$f);
$count=count(explode("\n",$f));
But for some reason it does not eliminate white-spaces. Is there a better way to get this done?
The following code does the job, since I don’t care much about the spaces, but I still wonder, why my original line labeled “does not work” is not removing spaces from empty lines. Is there some extra character at the end? File format is unix.
$f=preg_replace('/ */','',$f); // removes all spaces properly.
Change
/^[\s\t]*$/to be/^\s*$/msand that should fix it.The
\sclass includes tabs, so no need to add\t. Thesmakes it match newline characters and themoption makes^and$work when data contains multiple lines (matches line breaks).Also, it might be better to change
/\n\n/sto be/[\r\n]{2,}/.