lococobra Posted November 6, 2009 Share Posted November 6, 2009 I'm having trouble catching comments inside php code. Could someone help me revise my regex or tell me how I can make this work properly. My comment detection regex is: ~//.*?[\n\r]~ and ~/\*(.*?)\*/~s The problem is this... $test = 'http://google.com'; <- is not a comment! How can I get this regex so it doesn't catch anything inside strings? Quote Link to comment https://forums.phpfreaks.com/topic/180497-comment-detecting-regex/ Share on other sites More sharing options...
rajivgonsalves Posted November 6, 2009 Share Posted November 6, 2009 regexp should be ~^//.*?[\n\r]~ and ~^/\*(.*?)\*/~s "^" denotes at the start Quote Link to comment https://forums.phpfreaks.com/topic/180497-comment-detecting-regex/#findComment-952215 Share on other sites More sharing options...
lococobra Posted November 6, 2009 Author Share Posted November 6, 2009 Doesn't exactly help. Comments aren't always at the beginning of lines. Quote Link to comment https://forums.phpfreaks.com/topic/180497-comment-detecting-regex/#findComment-952258 Share on other sites More sharing options...
rajivgonsalves Posted November 6, 2009 Share Posted November 6, 2009 you can use the inbuilt php tokenizer : example <?php $str = '<?php $test = "http://www.google.com"; // made it // more comments echo "what are comments about"; ?> '; $tokens = token_get_all($str); foreach ($tokens as $token) { if ($token[0] == T_COMMENT || $token[0] == T_DOC_COMMENT) { // This is a comment ;-) var_dump($token); } } ?> Quote Link to comment https://forums.phpfreaks.com/topic/180497-comment-detecting-regex/#findComment-952263 Share on other sites More sharing options...
lococobra Posted November 8, 2009 Author Share Posted November 8, 2009 That's the ticket! Thanks that was exactly what I needed :] Quote Link to comment https://forums.phpfreaks.com/topic/180497-comment-detecting-regex/#findComment-953798 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.