ragax Posted February 6, 2012 Share Posted February 6, 2012 Here is a problem that arose to someone I was helping over PM. I thought I'd post the answer here as PM answers don't help grow the forum's knowledge base. The problem ("idealized"): Why does this return "Nope"? <?php $string='R2'; if (preg_match('~ (?x) # Comments Mode \w # One word character \d # One digit ~',$string)) echo 'Yep'; else echo 'Nope'; ?> Answer: because you turned on comment mode in mid-expression From the starting delimiter ~ to the point where comment mode is turned on (?x), you have a couple spaces and a carriage return. The regex engine first tries to match those spaces and carriage return, then only does it turn on comment mode, then it tries to match a word character and a digit. So R2 will not match. This would work: <?php $string='R2'; if (preg_match('~(?x) # Comments Mode \w # One word character \d # One digit ~',$string)) echo 'Yep'; else echo 'Nope'; ?> Conclusion: In most cases you'll want to have (?x) at the beginning of your patterns. If you have (?x) later on, just be aware that everything before it will be matched in regular (non-comment) mode. Also a reminder: if using comment mode, if you need to match a space character, either use \s or [ ] as the engine will ignore any spaces in the expression past the (?x). Wishing you all a fun week! Quote Link to comment https://forums.phpfreaks.com/topic/256500-a-quick-tip-about-comment-mode-x/ 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.