Forum Moderators: coopster
I am trying to validate a form field. I have provided an example below. Basically I want to check that 'a' ($findme) is the 1st and 2nd character in the string (0 and 1 position).
<?php
$mystring = 'aakjhabc';
$findme = 'a';
$pos = strpos($mystring, $findme);
// Note our use of ===. Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === 0) {
echo "The string '$findme' is the $pos digit";
} else {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
}
?>
I am wondering, can strpos be used to find the specific character more than once in the string? As you see above, the 'aa' is the first 2 characters in the string. $pos equals 0 because it finds the first 'a' in the string, and I guess it doesn't look for the 2nd 'a'? If strpos can't be used for what I want, what other method can I use? I'd like to keep it in an IF statement and relatively simple. Any help much appreciated. Thanks for reading.
once to find the zero,
strpos($haystack, $findme)
and next with an offset of 1
strpos($haystack, $findme, 1) so you get 1.
you can't just use ($haystack, $findme) where $findme=aa because aa can be anywhere in the string.
thanks for getting me to think.