0

Can't find a solution to this which seems simple enough. I have user input field and want to check the user has prefixed the code asked for with an S (example code S123456 so I want to check to make sure they didn't just put 123456).

// Function to check string starting with s

if (isset($_REQUEST['submitted'])) { $string=$_POST['required_code'];function startsWith ($string, $startString){$len = strlen($startString);return (substr($string, 0, $len) === $startString);
}
  
// Do the check 
if(startsWith($string, "s"))echo "Code starts with a s";else echo "Code does not start with a s";}

The problem is if the user inputs an upper case S this is seen as not being a lower case s.

So I can get round this using

$string = strtolower($string);

So if the user inputs an uppercase S it gets converted to lower case before the check. But is this the best way? Is there not someway to say S OR s? Any suggestions?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
  • That Code tag thing doesn't seem to work here. I put the code in the required tags using Ctrl K but it's not come out right. – RobertMallett Aug 16 '22 at 11:41
  • To mark a _block_ of text as code, you need to use _three_ "backticks", or indent _all_ the lines of the code; see https://stackoverflow.com/editing-help#code I've fixed your post for you, you can see what I edited here: https://stackoverflow.com/posts/73373408/revisions – IMSoP Aug 16 '22 at 11:44
  • the way you check it is best practice, to my knowledge. Just set the string to check and the input string to the same - either upper or lowercase and you're fine – SteelNation Aug 16 '22 at 11:48
  • There are case-insensitive recommendations at [the canonical page](https://stackoverflow.com/q/834303/2943403) and the duplicates which point to it. Here is [a related topic](https://stackoverflow.com/q/63121737/2943403). – mickmackusa Aug 17 '22 at 13:37
  • If you are validating the user input, why not validate the entire input at the same time? `preg_match('/^S\d+$/', $input)` If the goal is to sanitize the string then you could do something like `$sanitized = preg_replace('/^\D*(\d+).*/s', 'S$1', $input, 1, $count);` which would sanitize the input and `if ($count)` would mean that the input contained at least one digit. Standardizing/Sanitizing user input is a fundamental technique that will ensure that subsequent processes can run seamlessly. – mickmackusa Aug 17 '22 at 22:28

3 Answers3

4

What you could do instead of creating your own function, is using stripos. Stripos tries to find the first occurrence of a case-insensitive substring.

So as check you could have:

if(stripos($string, "s") === 0)

You need 3 equal signs, since stripos will return false (0) if it can't find the substring.

Kevin
  • 1,068
  • 5
  • 14
  • 16
3

Take your pick; there are many ways to see if a string starts with 'S'. Some of them case-sensitive, some not. The options below should all work, although I wouldn't consider any of them better than your current solution. stripos() is probably the 'cleanest' check though. If you need multibyte support, there's also the mb_stripos() variant.

(Although; keep in mind that stripos() can also return false. If you're going with that option, always use the stricter "identical" operator ===, instead of == to prevent type juggling.)

if (stripos($string, 's') === 0) {
    // String starts with S or s
} else {
    // It does not
}
if (str_starts_with($string, 's') || str_starts_with($string, 'S')) // ...
if (in_array(substr($string, 0, 1), ['S', 's'], true)) // ...
if (preg_match('/^s/i', $string)) // ...
// Many other regexp patterns also work
Duroth
  • 6,315
  • 2
  • 19
  • 23
  • 3
    for regex you can also use the insenstive flag i.e. `preg_match('/^s/i')` – apokryfos Aug 16 '22 at 11:58
  • 1
    Note that when it comes to case sensitivity, "multibyte support" opens up a whole can of worms - Is "ß" a case-insensitive match for "ss", or perhaps for "sz"? How to handle [the two forms of i in Turkish](https://en.wikipedia.org/wiki/Dotted_and_dotless_I_in_computing)? And so on. The most comprehensive approach is to use the ICU's collation definitions, implemented in PHP as [the Collation class](https://www.php.net/manual/en/class.collator.php) in the intl extension. – IMSoP Aug 16 '22 at 13:48
0

Thanks all, it was

if (str_starts_with($string, 's') || str_starts_with($string, 'S')) // ...

I was looking for I had tried

if (str_starts_with($string, 's' || 'S')) // ...