Supertrooper Posted August 18, 2012 Share Posted August 18, 2012 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 Quote Link to comment https://forums.phpfreaks.com/topic/267283-substr-help/ Share on other sites More sharing options...
Christian F. Posted August 18, 2012 Share Posted August 18, 2012 For this you'd want to use Regular Expressions: if (preg_match ('/^(?:ab|ba)/i', $string)) { // String starts with ab or ba, case insensitive. } PS: Please use the tags around code you post here. It makes both the code, and your post, a lot easier to read. Thanks. Quote Link to comment https://forums.phpfreaks.com/topic/267283-substr-help/#findComment-1370492 Share on other sites More sharing options...
rythemton Posted August 18, 2012 Share Posted August 18, 2012 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. Quote Link to comment https://forums.phpfreaks.com/topic/267283-substr-help/#findComment-1370494 Share on other sites More sharing options...
Supertrooper Posted August 18, 2012 Author Share Posted August 18, 2012 OK thanks guys. Quote Link to comment https://forums.phpfreaks.com/topic/267283-substr-help/#findComment-1370497 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.