Jump to content

Substr help


Supertrooper

Recommended Posts

Hello,

 

Ok, so I am passing something through via a web form and I want to check if the first 2 letters contain something so I have worked out you can do:

 

if (substr($foobar, 0, 2) === 'ab')

 

{ echo "blah blah"; }

 

What happens if I want to check if the first two letters are ab or ba?

 

I thought I could do

 

 

if (substr($foobar, 0, 2) === 'ab' or 'ba')

 

{ echo "blah blah"; }

 

but this doesn't seem to work.

 

Also, what if I want to check for all variants of CAPS for example, AB, ab, Ab, bA etc?

 

Thanks

Link to comment
Share on other sites

Your second bit of code doesn't work the way you think it does:

if (substr($foobar, 0, 2) === 'ab' or 'ba') // This won't work right

This is going to check if the first two characters is 'ab', then it's going to check to see if 'ba' is TRUE or FALSE, which will be always TRUE because a nonempty string is considered TRUE in PHP. So you can see this better, here is your code again using parenthesis to show order of precedence:

if ( ( substr($foobar, 0, 2) === 'ab' ) or ( 'ba' ) ) 

You'll need to do the comparison twice for it to work right:

if (substr($foobar, 0, 2) === 'ab' or substr($foobar, 0, 2) === 'ba') 

 

As for checking variation in Caps, there are many ways you could go. One of the easiest in this case would be to force the results to be lowercase:

if (strtolower(substr($foobar, 0, 2)) === 'ab' or strtolower(substr($foobar, 0, 2)) === 'ba') 

 

You can see more of PHP order of precedence at http://php.net/manual/en/language.operators.precedence.php

 

For more complicated checks, you can also use regular expressions, which can shorten your code.

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.