phparraysstringtokenizetext-parsing

Tokenize a string containing multiple delimiters into an array of associative arrays


From the following string:

I am looking for {{ attribute_a }} with {{ attribute_b }} to make {{ attribute_c }}

I am trying to create the following array structure:

[
   [0] => [
      "type" => "text", 
      "content" => "I am looking for"
   ], 
   [1] => [
      "type" => "dropdown", 
      "name" => "attribute_a"
   ], 
   [2] => [
      "type" => "text",
      "content" => "with"
   ],
   [3] => [
      "type" => "dropdown", 
      "name" => "attribute_b"
   ], 
   [4] => [
      "type" => "text",
      "content" => "to make"
   ],
   [5] => [
      "type" => "dropdown", 
      "name" => "attribute_c"
   ]
]

So the string needs to be cut into parts with "{{ * }}" as a delimiter. But then I need the value inside the delimiter too.


Solution

  • With the help of Your Common Sense and CBroe I figured it out:

    $result = [];
    $pattern = '/(\{\{[^}]*\}\})/';
    $lines = preg_split( $pattern, $structure, null, PREG_SPLIT_DELIM_CAPTURE );
       foreach ( $lines as $line ) {
          preg_match( $pattern, $line, $matches );
          if ( $matches ) {
             $result[] = [
                'type' => 'dropdown',
                'name' => trim( str_replace( ['{{', '}}'], "", $line ) )
             ]; 
          } else {
             $result[] = [
                'type' => "text",
                'content' => trim( $line )
             ];
          }
    }