如何将含{{ }}分隔符的字符串转换为指定关联数组结构
字符串转指定关联数组解决方案
需求说明
给定输入字符串:
I am looking for {{ attribute_a }} with {{ attribute_b }} to make {{ attribute_c }}
需转换为以下结构的关联数组:
[ [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" ] ]
转换规则
- 以
{{ 内容 }}格式的标签作为分隔依据,拆分原字符串 - 标签外的文本片段,生成
text类型的数组项,包含content属性,值为去除首尾空格后的文本 - 标签内的内容,生成
dropdown类型的数组项,包含name属性,值为去除首尾空格后的标签内容
实现代码(PHP)
$input = "I am looking for {{ attribute_a }} with {{ attribute_b }} to make {{ attribute_c }}"; // 正则匹配,同时捕获标签前的文本和标签内的变量名 preg_match_all('/(.*?)(?:{{\s*(.*?)\s*}}|$)/s', $input, $matches, PREG_SET_ORDER); $result = []; foreach ($matches as $match) { // 处理文本部分:非空则添加text类型项 $textContent = trim($match[1]); if ($textContent !== '') { $result[] = [ 'type' => 'text', 'content' => $textContent ]; } // 处理标签内的变量:非空则添加dropdown类型项 $dropdownName = trim($match[2]); if ($dropdownName !== '') { $result[] = [ 'type' => 'dropdown', 'name' => $dropdownName ]; } } // 输出结果 print_r($result);
代码说明
- 使用正则表达式
/(.*?)(?:{{\s*(.*?)\s*}}|$)/s匹配每一段文本和对应的标签内容,.*?确保非贪婪匹配,避免跨标签捕获 - 遍历匹配结果,分别处理文本部分和标签内容:
- 文本部分去除首尾空格后,若不为空则生成
text类型项 - 标签内容去除首尾空格后,若不为空则生成
dropdown类型项
- 文本部分去除首尾空格后,若不为空则生成
- 最终得到的
$result数组即为符合要求的结构
内容的提问来源于stack exchange,提问作者Robbert
相关产品推荐
相关产品推荐

