Tell me more ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I am using the following code to calculate text to code ratio. I think it is crazy that no one can agree on how to properly calculate the result. I am looking any suggestions or ideas to improve this code that may make it more accurate.

<?php
// Returns the size of the content in bytes
function findKb($content){
    $count=0;
    $order = array("\r\n", "\n", "\r", "chr(13)",  "\t", "\0", "\x0B");
    $content = str_replace($order, "12", $content);
    for ($index = 0; $index < strlen($content); $index ++){
        $byte = ord($content[$index]);
        if ($byte <= 127) { $count++; }
        else if ($byte >= 194 && $byte <= 223) { $count=$count+2; }
        else if ($byte >= 224 && $byte <= 239) { $count=$count+3; }
        else if ($byte >= 240 && $byte <= 244) { $count=$count+4; }
    }
    return $count;
}
// Collect size of entire code
$filesize = findKb($content);
// Remove anything within script tags
$code = preg_replace("@<script[^>]*>.+</script[^>]*>@i", "", $content);
// Remove anything within style tags
$code = preg_replace("@<style[^>]*>.+</style[^>]*>@i", "", $content);
// Remove all tags from the system
$code = strip_tags($code);
    // Remove Extra whitespace from the content
$code = preg_replace( '/\s+/', ' ', $code );
// Find the size of the remaining code
$codesize = findKb($code);
// Calculate Percentage
$percent = $codesize/$filesize;
$percentage = $percent*100;

echo $percentage;
?>

I don't know the exact calculations that are used so this function is just my guess. Does anyone know what the proper calculations are or if my functions are close enough for a good judgement.

share|improve this question
Your approach doesn't take media heavy content into consideration... – Yannis Rizos Oct 12 '12 at 10:56
Do you have any suggestions on how I could implement add those figures. – James Oct 12 '12 at 13:24
Just notice you already asked this on stack overflow, don't post exactly the same question on multiple sites please. – Yannis Rizos Oct 12 '12 at 13:29
I deleted that post as I was suggested to post the question here. – James Oct 12 '12 at 13:35
I'm sorry but that was some bad advice. Did you get a chance to read my comment there? – Yannis Rizos Oct 12 '12 at 13:37
show 5 more comments

closed as off topic by gnat, MainMa, Mark Trapp, Walter, Yannis Rizos Oct 12 '12 at 13:28

Questions on Programmers Stack Exchange are expected to relate to software development within the scope defined in the FAQ. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about closed questions here.

Browse other questions tagged or ask your own question.