Welcome to WebmasterWorld Guest from

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

strpos help

2:19 am on Jul 8, 2007 (gmt 0)

New User

5+ Year Member

joined:Aug 19, 2006
votes: 0


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).

$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.

7:57 am on July 8, 2007 (gmt 0)

New User

5+ Year Member

joined:Aug 19, 2006
votes: 0

Nevermind, I found a solution.
7:12 am on July 9, 2007 (gmt 0)

Junior Member

10+ Year Member

joined:Oct 6, 2004
votes: 0

yep, i was playing with your code here.. I think this is what you found out. strpos will only find the first occurrence in the string, so you have to run it twice:

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.