+ Reply to Thread
Page 1 of 3 123 LastLast
Results 1 to 10 of 29

Thread: extracting from a string

  1. #1
    garrensilverwing's Avatar
    garrensilverwing is offline x10 Sophmore garrensilverwing is an unknown quantity at this point
    Join Date
    Nov 2008
    Posts
    148

    extracting from a string

    to try and speed up the process of adding chess games to my website i would like a piece of code that will search a large string for certain bits of information, so instead of hand typing them into the database every time i could just enter the string and it will do the job for me. here is an example of what i want to do:

    Code:
    [Event "Wyoming Open"]
    [Site "Laramie College"]
    [Date "2006.05.06"]
    [Round "3"]
    [White "James Kulbacki"]
    [Black "Chris Peterson"]
    [Result "0-1"]
    [ECO "A00"]
    [WhiteElo "1880"]
    [BlackElo "1668"]
    [PlyCount "38"]
    [EventDate "2006.??.??"]
    [TimeControl "35/90:0"]
    
    1. b4 e5 2. Bb2 Bxb4 3. f4 Nc6 4. fxe5 f6 5. exf6 Nxf6 6. Nf3 O-O 7. g3 Ng4 
    8.c3 Bc5 9. d4 Qe7 10. Qd3 d5 11. dxc5 Bf5 12. Qxd5+ Kh8 13. Nbd2 Rad8 
    14. Qb3 Qe3 15. c4 Qf2+ 16. Kd1 Rxd2+ 17. Kxd2 Rd8+ 18. Kc1 Ne3 
    19. Nd2 Qe1+ 
    0-1
    this is a PGN format chess game. i need to extract the first and last names (seperately) for both white and black, both their ratings, the ECO, the result and the year. the rest of the information can be discarded. I have no idea how to do this and tutorials online are not very helpful so thanks in advance
    Last edited by garrensilverwing; 05-20-2009 at 09:36 PM.

  2. #2
    garrettroyce's Avatar
    garrettroyce is offline Generally Helpful Member garrettroyce is a glorious beacon of lightgarrettroyce is a glorious beacon of light
    Join Date
    Apr 2008
    Location
    IL, USA
    Posts
    3,746

    Re: extracting from a string

    Code:
    $strings = explode('[', $string); //every time a [ is encountered, a new string is added to the array $strings
    $white = substr($strings[4], 6, -2); // white is the 4 element (from zero), name starts after 7th char (from zero) remove last 2 chars "]
    $white_first = strstr($white, ' '); // get everything before and including the first space in white's full name
    $white_last = substr($white, strlen($white_first)); // get everything after the first space in white's full name
    $white_first = substr($while, 0, -1); // remove the last char (space) from white's first name
    $white_rating = substr($strings[8], 9, -2); // white's rating is 8th from zero string, starts after 9 chars, drop last 2 chars
    $result = substr($strings[6], 9, -2); // you get the picture by now :)
    $year = substr($strings[11], 11, 4); // year is always 4 chars long
    I'll leave black up to you, I'm going to bed :P
    Last edited by garrettroyce; 05-20-2009 at 09:58 PM.
    gjr.gr - coming soon: secrets of OCD coding from a self taught tinkerer

  3. #3
    misson is offline x10 Spammer misson is a jewel in the rough
    Join Date
    Mar 2008
    Location
    Libertatia
    Posts
    2,506

    Re: extracting from a string

    Regular expressions are the easiest way to do it, though REs can be hard to learn. Studying the relationship between regular languages and finite state machines will give you the best understanding. You could also try MDC RE guide or the Perl RE tutorial

    For example, /\[(White|Black) ".* ([A-Za-z']+)"\]/ will match and extract the player's color and last name. What language do you want to use to translate the data?

  4. #4
    garrensilverwing's Avatar
    garrensilverwing is offline x10 Sophmore garrensilverwing is an unknown quantity at this point
    Join Date
    Nov 2008
    Posts
    148

    Re: extracting from a string

    Quote Originally Posted by misson View Post
    Regular expressions are the easiest way to do it, though REs can be hard to learn. Studying the relationship between regular languages and finite state machines will give you the best understanding. You could also try MDC RE guide or the Perl RE tutorial

    For example, /\[(White|Black) ".* ([A-Za-z']+)"\]/ will match and extract the player's color and last name. What language do you want to use to translate the data?
    i was hoping to do it in php so i dont have to fiddle with any more types of code lol

  5. #5
    garrettroyce's Avatar
    garrettroyce is offline Generally Helpful Member garrettroyce is a glorious beacon of lightgarrettroyce is a glorious beacon of light
    Join Date
    Apr 2008
    Location
    IL, USA
    Posts
    3,746

    Re: extracting from a string

    mission's answer is php code, it uses a more complex system. Regular expressions are extremely powerful, and even though the rules are simple, they are difficult to master. If you were to go mission's route, it will definitely be a good tool for you to use in the future, but it will take a lot of patience and learning. My route is very simple, but it takes more code to do the same thing.
    gjr.gr - coming soon: secrets of OCD coding from a self taught tinkerer

  6. #6
    garrensilverwing's Avatar
    garrensilverwing is offline x10 Sophmore garrensilverwing is an unknown quantity at this point
    Join Date
    Nov 2008
    Posts
    148

    Re: extracting from a string

    well im not too worried about length of code right now because sometimes you have to do things the hard way first and im doing everything else the hard way and then converting it when i get it working which is probably an ass backwards way of doing it but i am learning so much

  7. #7
    misson is offline x10 Spammer misson is a jewel in the rough
    Join Date
    Mar 2008
    Location
    Libertatia
    Posts
    2,506

    Re: extracting from a string

    To illustrate the utility of regular expressions, here are some example functions for this problem. pgn2array will turn a string containing PGN formatted pairs into an associative array.
    PHP Code:
    function parseName($name) {
        
    preg_match('/^(?:(\S+) (?:(.*) )?)?(\S+)$/'$name$name);
        return 
    array_combine( array('full''first''middle''last'), $name);
    }

    function 
    parseDate($date) {
        return 
    array_combine(array('year''month''day'), explode('.'$date));
    }

    function 
    pgn2array($pgn) {
      static 
    $filters = array('white' => 'parseName''black' => 'parseName'
                              
    'date' => 'parseDate''eventdate' => 'parseDate');
      
    $arr=False;
      if (
    preg_match_all('/\[(\w+) "([^"]+)"\]/'$pgn$matchesPREG_PATTERN_ORDER)) {
          
    $arr array_combine(array_map('strtolower'$matches[1]), $matches[2]);
          foreach (
    $filters as $key => $filter) {
              
    $arr[$key] = call_user_func($filter$arr[$key]);
          }
      }
      return 
    $arr;

    If the data is stored in a file, the above would require you to read the whole file before parsing it. To parse a file in place, try:
    PHP Code:
    function filterTagPair($key$value) {
        switch(
    $key) {
        case 
    'white':
        case 
    'black':
            return 
    parseName($value);
            break;
        case 
    'date':
        case 
    'eventdate':
            return 
    parseDate($value);
            break;
        }
        return 
    $value;
    }

    function 
    pgnFile2array($file) {
        
    $arr = array();
        
    $fpos ftell($file);
        while (!
    feof($file) && $line=fgets($file)) {
            if (
    preg_match('/\[(\w+) "([^"]+)"\]/'$line$matches)) {
                
    $matches[1] = strtolower($matches[1]);
                
    $matches[2] = filterTagPair($matches[1], $matches[2]);
                
    $arr[$matches[1]] = $matches[2];
                
    $fpos ftell($file);
            } else {
                
    fseek($file$fpos);
                break;
            }
        }
        return 
    count($arr) ? $arr False;

    Looping over an array of filters (as pgn2array does) would work just as well for pgnFile2array. I used a switch to illustrate another approach.

    None of the above deals with errors, so they could be fleshed out in this regard.
    Last edited by misson; 05-21-2009 at 08:50 PM. Reason: fixed code errors

  8. #8
    xav0989's Avatar
    xav0989 is offline Community Public Relation xav0989 is just really nice
    Join Date
    Jul 2008
    Location
    ifk
    Posts
    4,438

    Re: extracting from a string

    Quote Originally Posted by garrensilverwing View Post
    well im not too worried about length of code right now because sometimes you have to do things the hard way first and im doing everything else the hard way and then converting it when i get it working which is probably an ass backwards way of doing it but i am learning so much
    Well in this case, the hard way, regular expressions, is also the best way!
    Xavier L | Community Public Relations Manager (Free Hosting Support)
    █ Yes, my position is too cool to even exist!
    How am I helping? Rate this post by clicking the icon below! (this is even better than "liking" a post)
    Terms of Service | Acceptable Use Policy | x10Hosting Wiki

  9. #9
    misson is offline x10 Spammer misson is a jewel in the rough
    Join Date
    Mar 2008
    Location
    Libertatia
    Posts
    2,506

    Re: extracting from a string

    As for the power of regular expressions, XKCD says it best:


  10. #10
    xav0989's Avatar
    xav0989 is offline Community Public Relation xav0989 is just really nice
    Join Date
    Jul 2008
    Location
    ifk
    Posts
    4,438

    Re: extracting from a string

    Nice one there, mission!
    Xavier L | Community Public Relations Manager (Free Hosting Support)
    █ Yes, my position is too cool to even exist!
    How am I helping? Rate this post by clicking the icon below! (this is even better than "liking" a post)
    Terms of Service | Acceptable Use Policy | x10Hosting Wiki

+ Reply to Thread
Page 1 of 3 123 LastLast

Similar Threads

  1. Query String - $_GET problem
    By stevet70 in forum Programming Help
    Replies: 5
    Last Post: 04-15-2009, 02:37 PM
  2. PHP found in string help
    By Chris S in forum Programming Help
    Replies: 9
    Last Post: 04-06-2009, 12:08 PM
  3. C Dynamic String Allocation
    By souradipm in forum Programming Help
    Replies: 2
    Last Post: 11-22-2008, 02:26 PM
  4. Split string
    By radofeya in forum Programming Help
    Replies: 3
    Last Post: 10-02-2008, 02:35 AM
  5. forums?
    By twin2t7 in forum Free Hosting
    Replies: 17
    Last Post: 11-20-2007, 03:08 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
x10hosting free hosting for the masses
dedicated servers