[英]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.但是我也需要分隔符内的值。
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.