problem using an array element and substr

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
Hi, just new to the list, but couldn't find anything about this on
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:
"%                              999990008312?;0008312999990000?"
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],0,5); // first 5 chars from original
string excluding the % and all spaces
$card_id = substr("$card_data[0]",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
done anyway?


Patrick Londema

Debian GNU/Linux Testing
PHP Version 4.1.2
Working demo hosted on DSL line @ /

Re: problem using an array element and substr

EvilPlatypus wrote (in part):

Quoted text here. Click to load it
if I

Before you change any code, print out the value of $card_string after
the trim. You will see that it is

"                              999990008312?;0008312999990000?".

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.


Site Timeline