Jump to content

A quick tip about comment mode (?x)


ragax

Recommended Posts

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!

 

:)

 

 

Link to comment
https://forums.phpfreaks.com/topic/256500-a-quick-tip-about-comment-mode-x/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.