简体   繁体   中英

Split string into associative array by multiple delimiters

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM