使用 PHP 和 MySQL。我需要做一些类似于 Github 在显示源代码时所做的事情,
122 行(98 sloc)4.003 kb
我需要从 MySQL 数据库结果中获取 Lines Of Code
和 Source Lines Of Code
的总数。
源代码将在 wordpress 表中作为元字段,我知道如何使用文件完成此操作,但不知道如何使用数据库结果。然后我还需要计算此字段上使用的磁盘空间以显示类似 4.003 kb
如果你知道怎么做,我将不胜感激
更新
这个非常难看的代码是目前为止我找到的唯一解决方案,如果你搜索 SO 或谷歌,所有结果都显示如何计算 FILE 上的代码行数,我的问题非常不同,我不是在获取文件,我有一个 MySQL 数据库的结果保存在 $variable
下面的代码做了 3 件事中的 1 件事,它计算了 (LOC) 的总行数,所以我只需要获取 (SLOC) 和(已用磁盘空间),但是我非常愿意接受更好的计数方式变量的 LOC。
// Get LOC
$a = $code_source; // Variable holding our code
$result = count_chars($a, 0);
for ($i=0; $i < count($result); $i++) {
if ($result[$i] != 0) {
if (chr($i) == "\n") // line feed
$n = $result[$i];
if (chr($i) == "\r") // carriage return
$r = $result[$i];
}
}
if ($n > $r) $l = $n + 1;
if ($r >= $n) $l = $r + 1;
if (!isset($l) ) $l = "2";
echo "Line Of Code = " . $l;
空间
//Get Disk Space Used
if (function_exists('mb_strlen')) {
$size = mb_strlen($code_source, '8bit');
} else {
$size = strlen($code_source);
}
if($size >= 1024)
$size = round($size / 1024, 2).' KB';
else
$size = $size.' bytes';
echo 'size of file' . ': ' . $size;
第二次更新
好的,这是我现在得到的最终结果,我省略了@refp 的 (LOC) 代码,因为出于某种原因我无法让它工作,我确实使用了他的 SLOC 代码并将所有代码都放入了一个可用的类中。请填写免费改进
class SourceCodeHelper{
// Count total number of Lines (LOC)
public function countLOC($string){
$result = count_chars($string, 0);
for ($i=0; $i < count($result); $i++) {
if ($result[$i] != 0) {
if (chr($i) == "\n\n") // line feed
$n = $result[$i];
if (chr($i) == "\r") // carriage return
$r = $result[$i];
}
}
if ($n > $r) $l = $n + 1;
if ($r >= $n) $l = $r + 1;
if (!isset($l) ) $l = "2";
//substr_count ($data, "\n") + 1;
return $l;
}
// Count total Source code lines of Code (SLOC)
public function countSLOC($string){
return count(preg_split("/\n\s*/", $string));
}
// Calculate disk space usage of string
public function stringDiskSpace($string){
if (function_exists('mb_strlen')) {
$size = mb_strlen($string, '8bit');
} else {
$size = strlen($string);
}
return diskSpacePretty($size);
}
// Format a disk space usage into human readable format
public function diskSpacePretty($size){
if($size >= 1024)
$size = round($size / 1024, 2).' KB';
else
$size = $size.' bytes';
return $size;
}
最佳答案
没有直接的方法从 mysql 内部计算字段中的行数。
相反,我建议您在存储行数的表中附加一个新列。使用 PHP(或任何负责插入数据的后端语言)计算 LOC/SLOC,并在需要时更新它。
要计算字符串中的行数 (LOC),您可以使用 substr_count这将计算第二个参数字符串在第一个参数字符串中出现的次数。
在下面的示例中,我们将计算 \n
在 $data
中出现的次数。
substr_count ($data, "\n") + 1; // since one \n creates two lines
要计算您可以使用的 SLOC 数量 preg_split过滤掉所有空行(长度为 0 或仅包含空格的行)
count (preg_split ("/\n\s*/", $data))
关于php - 计算数据库字段上的代码行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8497010/