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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help with Good Programming Practices 1

Status
Not open for further replies.

sen5241b

IS-IT--Management
Sep 27, 2007
199
US
I seem to get errors a lot because strlen just gives the length but positions with a string are different because the first char is position zero.

When determining whether a given position within a string is out of range (passed the the end of string) sometimes I use '>=' other times I compare the position with ($strLen - 1). Is there a good way to consistently deal with this?
 
i am not sure that i understand. how can strpos (the function for positions that i assume you are using) return a value that is larger than the length of the string itself?

sfaik if you take the 26 letters of the alphabet and do the following:

Code:
$pos = strpos($alphabet, 'z');
$pos will be assigned the value of 25.

perhaps a real world example would help?
 
Hi

I think sen5241b is asking about situations like this :
PHP:
[navy]$text[/navy][teal]=[/teal][green][i]'HelloWorld'[/i][/green][teal];[/teal]
[navy]$newthing[/navy][teal]=[/teal][green][i]' '[/i][/green][teal];[/teal]
[navy]$insert_at_position[/navy][teal]=[/teal][purple]5[/purple][teal];[/teal]

[gray]// condition #1[/gray]
[b]if[/b] [teal]([/teal][navy]$insert_at_position[/navy][teal]>=[/teal][COLOR=darkgoldenrod]strlen[/color][teal]([/teal][navy]$text[/navy][teal]))[/teal] [b]die[/b][teal]([/teal][green][i]'Can not insert there'[/i][/green][teal]);[/teal]

[gray]// condition #2[/gray]
[b]if[/b] [teal]([/teal][navy]$insert_at_position[/navy][teal]>[/teal][COLOR=darkgoldenrod]strlen[/color][teal]([/teal][navy]$text[/navy][teal])-[/teal][purple]1[/purple][teal])[/teal] [b]die[/b][teal]([/teal][green][i]'Can not insert there'[/i][/green][teal]);[/teal]

[navy]$text[/navy][teal]=[/teal][COLOR=darkgoldenrod]substr_replace[/color][teal]([/teal][navy]$text[/navy][teal],[/teal][navy]$newthing[/navy][teal],[/teal][navy]$insert_at_position[/navy][teal],[/teal][purple]0[/purple][teal]);[/teal]
Personally I prefer #1.

Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top