Jump to content

Problem with ereg and backslashes


mottwsc

Recommended Posts

I'm allowing users to send an email as an invitation.  I pre-fill it (using \n for new line, let them edit it and check if after that.  I always get a negative response in the ereg when including \ in the string, and I can't figure out how to fix it.  Any suggestions?

 

$invitationClean = "Hello,\n\nYou are invited.";
if( !ereg("^([A-Za-z0-9',. -!\\]{0,250})+$", $invitationClean) )
{ echo "invitationClean - bad data<br>"; }
else
{ echo "invitationClean - OK data<br>"; }

 

Link to comment
Share on other sites

There are some issues with your code:

 

- Since you are using double quotes for your $invitationClean variable, \n becomes a newline, so you can use the hex \x0A to match this...

- I would advise not using ereg, as by default come PHP 6, this will not be supported. Use preg instead.

- In your character class, you use a dash somewhere in the middle.. this automatically becomes a range.. when using a dash in such circumstances, you need to declare the dash as the very first or very last character in the character class.

 

So here is my attempt:

$invitationClean = "Hello, \n\n You are invited.";
if( preg_match("#^(?:[ a-z0-9'.,!-]|\x0A)+$#i", $invitationClean) && strlen($invitationClean) < 251 ){ 
echo 'invitationClean - OK data <br />';
} else { 
echo 'invitationClean - bad data <br />'; 
}

 

I urge you to view this link and this link to learn more about preg (as it will take too much time to properly type out full fledged explanations here).

 

Hope this helps..

 

cheers,

 

NRG

 

 

Link to comment
Share on other sites

Also, I'd suggest always using single quotes for regular expressions so that you don't have escaping dilemmas. >_<

 

Good point... I typically use only single quotes as a rule.. so a re-write could look like this:

 

$invitationClean = 'Hello, \n\n You are invited.';
if( preg_match('#^[\\\ a-z0-9\'.,!-]+$#i', $invitationClean) && strlen($invitationClean) < 251 ){ 
echo 'invitationClean - OK data <br />';
} else { 
echo 'invitationClean - bad data <br />'; 
}

 

So in this case, I still do require an escape (the ' in the pattern). No big deal though.

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.