Identifying Comments in A Source Code Using Regular Expression

Here is a PHP code which will open any source code file and determines all the occurances of comments ( /* … */ and //) and prints the comments.

<?php
function get_comments($text){

$reg_exp = ‘((/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/)|(//.*))’;
preg_match_all($reg_exp, $text, $matches);
$usedPatterns = array();
foreach($matches[0] as $pattern){
if(!array_key_exists($pattern, $usedPatterns)){
$usedPatterns[$pattern]=true;
echo $pattern=$pattern.” \n “;

}
}
}
$_fp = fopen(“source_code.txt”, “r”);
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
$str=””;
while(!feof($_fp))
{
$str=$str.fgets($_fp);
}
get_comments($str);
?>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s