Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

PHP equivalent to index.Of 2

Status
Not open for further replies.

brownfox

Programmer
Joined
Jan 5, 2003
Messages
173
Location
GB
Does any on know the PHP equivalent to javascript's index.Of?
Some people are using this sign: &
in their usernames and it's screwing up my code later on.I want to alert them that this char is not allowed in their usernames. Thanks in advance for any help
 
make sure you follow the documentation for this function CAREFULLY, there's a tricky variable type pothole with it.

If the string you are searching for is not found in the bigger string, strpos returns FALSE, not -1 (as other languages like javascript do).

So, if you are using this function to determine whether or not a substring (or single character) exists, at any position, including position 0, and you just say:

Code:
if (strpos($biggerstr,"&") >= 0)

this will produce a TRUE even if the & is not found, because the FALSE that is returned from strpos will be typecast on-the-fly to an integer for comparison with 0, and FALSE will == 0, and the ">= 0" check will return true.

As the documentation says, to guard against this, you need to do stronger type checking in your test:

Code:
if (strpos($biggerstr,"&") !== false)

the operator === (three ='s) does an equality check that is type sensitive, meaning 0 does NOT === false, even though 0 == false. So, using !== will make sure that strpos does NOT return a false, but it can return any numbered position, including 0, and you'll be fine.

My other suggestion here is to consider just making the assumption for the user that this character (and possibly others that you want to make "illegal") are just not allowed, so if they enter them, you just remove them. This is very easily done with str_replace:

Code:
$biggerstr = str_replace("&","",$biggerstr);

This will take ANY number of the & characters found and replace them with empty strings, in effect removing them entirely.

This will reduce the need to report back to the user an error. Just a thought.
 
An easy solution would be to just check with a regular expression if any of the disallowed characters are in the username. You could also just allow PERL word chars:
Code:
if (preg_match('/\W/',$subject)){
   # error code
   ....
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top