homepage Welcome to WebmasterWorld Guest from 50.17.79.35
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Pubcon Platinum Sponsor 2014
Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

    
strpos help
joshm




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

Hello,

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.

 

joshm




msg:3388762
 7:57 am on Jul 8, 2007 (gmt 0)

Nevermind, I found a solution.

natural number




msg:3389288
 7:12 am on Jul 9, 2007 (gmt 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.

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved