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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.