PHP > string2array using a “template”

divide a string with a template. the “template dividers” are the keys for the output array.

  <?PHP
  function string2array ($string, $template){
    #search defined dividers
    preg_match_all ("|%(.+)%|U", $template, $template_matches);
    #replace dividers with "real dividers"
    $template = preg_replace ("|%(.+)%|U", "(.+)", $template);
    #search matches
    preg_match ("|" . $template . "|", $string, $string_matches);
    #[template_match] => $string_match
    foreach ($template_matches[1] as $key => $value){
     $output[$value] = $string_matches[($key + 1)];
    }
    return $output;
  }

  $string1 = 'www.something.com 66.196.91.121 - -
  [01/Sep/2005:04:20:39 +0200] "GET /robots.txt HTTP/1.0" 200 49 "-"';
  $string2= '  -  \[: \] "  "   ""';

  print_r (string2array ($string1, $string2));

  /*
  Array

  (
  [ServerAddress] => www.something.com
  [IP] => 66.196.91.121
  [User] => -
  [Date] => 01/Sep/2005
  [Time] => 04:20:39
  [TimeZone] => +0200
  [Method] => GET
  [Request] => /robots.txt
  [Protocol] => HTTP/1.0
  [ServerCode] => 200
  [Bytes] => 49
  [Referer] => -
  )
  */
 ?>

found on http://de.php.net/manual/en/function.split.php

Leave a Reply