problem using array and substr

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Patrick Londema

    problem using array and substr

    Hi,

    I'm trying to write a function that takes a string and splits this into 3
    distinct sections for a project I'm working on.

    This string in question has the following formet:
    "% 999990008312?;0 008312999990000 ?"
    The important bits i want to extract are the 1st and second numbers. In this
    example that is 99999 and 0008312. The sequence of 9's has a fixed length
    of 5 chars and the other number is whatever follows those 5 until the
    questionmark.

    My idea was to use explode to get the string up to the "?" and the use
    substr() to split the remaining string into the bits I want. Not being the
    greatest coder in the world I came up with this ($card_string is from the
    function call):
    $card_string = trim($card_stri ng, "%"); // get rid of the first char and
    all those annoying spaces
    $card_data = explode("?", $card_string);
    $card_ver = substr($card_da ta[0],0,5); // first 5 chars of string
    $card_id = substr("$card_d ata[0]",6); // all other chars

    I expected $card_ver to become "99999" and $card_id to contain "0008312",
    BUT what I actually get is $card_ver empty and $card_id "9999900083 12". If
    I insert a line $card_data[0] = "9999900083 12" this actually does happen,
    but if I knew the string's content, why would I write a function?
    Typecasting $card_data[0] to type string with either
    '$card_ver_stri ng_typed = (string) substr($card_da ta[0],0,5);' or
    $card_data_stri ng = "$card_data[0]" don't help either.

    Am I overlooking something, is this a very weird limitation of PHP or is
    there just an easier way of doing this alltogether?

    All help more than welcome!

    Patrick Londema
    Debian GNU/Linus Testing
    PHP 4.1.2
    Apache 1.3.26

    Hope this doesn't show up twice anywhere, newsreader gave me a really big
    error message when I tried to post...
  • Janwillem Borleffs

    #2
    Re: problem using array and substr

    Patrick Londema wrote:[color=blue]
    > My idea was to use explode to get the string up to the "?" and the use
    > substr() to split the remaining string into the bits I want. Not
    > being the greatest coder in the world I came up with this
    > ($card_string is from the function call):[/color]

    This is where the power of regular expressions kicks in:

    $s = "% 999990008312?;0 008312999990000 ?";

    if (preg_match("/(\d{5})(\d+)/", $s, $match)) {
    array_shift($ma tch);
    print_r($match) ;
    }
    [color=blue]
    > PHP 4.1.2[/color]

    Time to upgrade to the 4.3 branch at least...


    JW



    Comment

    Working...