finding lines ending in ")" with substr()

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
akronymn
Forum Newbie
Posts: 7
Joined: Wed Jul 02, 2008 12:31 pm

finding lines ending in ")" with substr()

Post by akronymn »

I'm running into an odd situation using substr(). I am trying to find all lines in a text file that end in a ")" or more accurately ")\n" using substr(). First I read in a line and then explode it into an array called $words. Then when I try

Code: Select all

 
if(substr($words[count($words) -1], -1) == "\n")
{...}
 
This returns all lines in the file as expected. But when I try

Code: Select all

 
if(substr($words[count($words) -1], -2) == ")\n")
 
or

Code: Select all

 
if(substr($words[count($words) -1], -2, 1) == ")")
 
It returns none of the lines and I'm not seeing why. I've tried several similar combinations all with no luck. Can anyone spot what I am doing wrong? Thanks! -adam
akronymn
Forum Newbie
Posts: 7
Joined: Wed Jul 02, 2008 12:31 pm

Re: finding lines ending in ")" with substr()

Post by akronymn »

Update: Figured it out...

so the solution was to use

Code: Select all

 
if(substr($words[count($words) -1], -3, 1) == ")")
 
apparently the \n counts as both 1 and 2 characters... interesting.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: finding lines ending in ")" with substr()

Post by John Cartwright »

Or you could trim() the string prior to searching it.
Post Reply