SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Addict beebs93's Avatar
    Join Date
    Jul 2010
    Location
    Vancouver, Canada
    Posts
    207
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Convert multi-line, colon-separated value list to array key/value pairs

    Hello,

    I can't figure out the most effecient way to covert this:

    Location: UK
    Feature Program: No
    Schedule: Active
    Visible: Yes
    Week: Weekday
    Notes:
    Happens on Friday. Usually.

    to:

    PHP Code:
    array('Location' => 'UK''Feature Program' => 'No''Schedule' => 'Active' ...) 
    I keep thinking that doing a couple explodes to break up the new lines then the colon-separated text while assigning the key or value to an array, but I was wondering if there's a better way to tackle this.
    "To be truly dedicated to something
    you must be willing to betray it.
    " -SW

  2. #2
    SitePoint Enthusiast
    Join Date
    Oct 2011
    Posts
    47
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    If your list is always in the same format with the same labels, you can use this super complicated rocket science grade regex-foreach combination:

    PHP Code:
    <?php

    $str 
    'Location: UK
    Feature Program: No
    Schedule: Active
    Visible: Yes
    Week: Weekday
    Notes:
    Happens on Friday. Usually.'
    ;

    $pattern "#((Location|Feature Program|Schedule|Visible|Week): (.*)\n|(Notes):[\s\n]+(.*)$)#Uis";

    preg_match_all($pattern$str$matchesPREG_SET_ORDER);

    $result = array();

    foreach(
    $matches as $match)
    {
            
    $length count($match);
            
    $result[$match[$length-2]] = $match[$length-1];
    }

    var_dump($result);

    ?>
    The output is:

    Code:
    array(6) {
      ["Location"]=>
      string(2) "UK"
      ["Feature Program"]=>
      string(2) "No"
      ["Schedule"]=>
      string(6) "Active"
      ["Visible"]=>
      string(3) "Yes"
      ["Week"]=>
      string(7) "Weekday"
      ["Notes"]=>
      string(27) "Happens on Friday. Usually."
    }


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
  •