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.

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)){
echo $pattern=$pattern.” \n “;

$_fp = fopen(“source_code.txt”, “r”);
/* Enter your code here. Read input from STDIN. Print output to STDOUT */


Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s