Do you have a question? Post it now! No Registration Necessary. Now with pictures!
- Posted on
- problem using an array element and substr
November 5, 2004, 1:06 am
rate this thread
google so I hope it's never been asked before.
I'm trying to write a function that takes a rather large (ASCII) string
and splits it into distict sections. The input string is beyond my
control since it will be read from a magnetic card (like a creditcard).
The string looks like this:
The important bits being the sequence of 9's and the number directly
behind. The 9 sequence has a fixed length, the remainder isn't. My idea
was to use explode("?", $string) to isolate the first section, strip of
the beginning and the use substr to split the remaining string in a part
of 5 and unknown length. I'm not the greatest coder in the world I'll
freely admit, but this is what I came up with ($card_string being the
string in question with the layout as above):
$card_string = trim($card_string, "%");
$card_data = explode("?", $card_string);
$card_ver = substr($card_data,0,5); // first 5 chars from original
string excluding the % and all spaces
$card_id = substr("$card_data",6); // the rest of the string
I expected to get $card_ver = 99999 and $card_id = 0008312, instead a
echo or print show $card_ver = and $card_id = 999990008312.
If I force card_data to be "999990008312" it does exactly that, but if I
knew the content of the string, i wouldn't need this function so
naturally this is not a solution.
Am I makeing somekind of horrible mistake, is this some kind of really
weird limitation of PHP or maybe is there a simpler way of getting this
Debian GNU/Linux Testing
PHP Version 4.1.2
Working demo hosted on DSL line @ http://evilplatypus.net/~platypus/test /
Re: problem using an array element and substr
Before you change any code, print out the value of $card_string after
the trim. You will see that it is
Your trim statement just trimed off the "%". Change that statement to
$card_string = trim($card_string, " %");
That should do the trick.
Whenever you're having problems with your logic, put echo, print, or
print_r statements after each statement that might be a problem.