SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Guru
    Join Date
    Nov 2004
    Location
    England
    Posts
    698
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)

    Find first character in a string of a certain type

    Hi guys,

    I'm going to go out on a limb and say that I need to use regex but could do with a bit of help here. I need to pass a string to a script which would be of this kind of format:

    ABCD123456

    The number of letters can vary, as can the number of, erm, numbers. It's also possible to have a single letter on the end, but I can deal with that easily enough.

    I basically need to split (explode?) the two sections, using the character type as a separator. Can anyone tell me how? A quick look through the PHP string functions didn't provide me with the answer.

    Thanks all

  2. #2
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2008
    Posts
    5,757
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    One way would be to walk through the string, character by character, testing its type using the ctype_*() functions.

    You could also do
    PHP Code:
    $s 'ABCD123456';
    preg_match('#(\D+)(\d+)#'$s$m);
    print_r($m); 
    \D means not a digit
    \d means digit

    There's many other ways as well.

  3. #3
    SitePoint Guru
    Join Date
    Nov 2004
    Location
    England
    Posts
    698
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    This seems to work for me:

    Code PHP:
    $in = 'ABC12341564841D';
    preg_match_all(
    "/(?<prefix>[A-Z]+)(?<nums>[0-9]+)(?<suffix>[A-Z])/",
    $in,    $out);

    Is that the best way do you think?

  4. #4
    @php.net Salathe's Avatar
    Join Date
    Dec 2004
    Location
    Edinburgh
    Posts
    1,397
    Mentioned
    65 Post(s)
    Tagged
    0 Thread(s)
    You could also use sscanf for something like this. An advantage (if you choose to see it that way) would be that the matched items can be given a discrete type. In the example below, $number would be an integer, not just a string containing digits.

    PHP Code:
    $subject 'ABC12341564841D';
    sscanf($subject'%[A-Z]%d%[A-Z]'$prefix$number$suffix);
    var_dump($prefix$number$suffix); 
    Salathe
    Software Developer and PHP Manual Author.

  5. #5
    SitePoint Guru
    Join Date
    Nov 2004
    Location
    England
    Posts
    698
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Ah, interesting. That's a new one on me. Thanks


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •