简体   繁体   English

通过多个分隔符将字符串拆分为关联数组

[英]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 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:在 Your Common Sense 和 CBroe 的帮助下,我想通了:

$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.如果不处理语法错误,我认为preg_match_all就足够了。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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