Home > Mobile >  Split string into associative array by multiple delimiters
Split string into associative array by multiple delimiters

Time:09-08

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.

  • If the part is outside the delimiter it is a type of text with content.
  • If it is inside the delimiter it is a type of dropdown with a property of the name.

CodePudding user response:

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 )
         ];
      }
}

CodePudding user response:

I think a preg_match_all is enough if no syntax errors are to be handled.

$result=[];
if( preg_match_all('~(\{\{[^\}] \}\})|([^{}] )~u',$structure,$match) ){
  foreach($match[0] as $item){
    $text = trim($item," {}\r\n");
    $result[] = strpos($item,"{{") !== false
      ? ["type" => "dropdown", "name" => $text]
      : ["type" => "text", "content" => $text] 
    ;
  }
}
  • Related