如何从XML导入的换行文本中提取配对子串组装为关联数组
现有逻辑的核心缺陷
- 按
<br>拆分原始文本后,没有清洗因换行产生的空白无效行,直接按原数组索引定位相邻内容会出现偏移错位 - 仅将命中关键词的属性标签存入普通索引数组,没有建立属性标签与紧邻下一行数值的映射关系,无法实现配对输出
- 缺少异常校验,遇到属性行后直接紧跟另一个属性行的特殊排版时,会出现数值错配的问题
改造后可直接运行的逻辑代码
if (!empty($arraywithvalues)) { // 按分隔符拆分原始文本,清洗无效空白行 $raw_split = explode("<br>", $arraywithvalues); $clean_rows = []; foreach ($raw_split as $line) { $trimmed_line = trim($line); // 跳过空字符串、纯空格的无效行 if ($trimmed_line !== '') { $clean_rows[] = $trimmed_line; } } // 重置为连续索引,避免之前的空值导致索引跳号 $clean_rows = array_values($clean_rows); // 存储最终的属性-数值配对结果 $paired_result = []; foreach ($clean_rows as $row_index => $row_content) { $lower_content = strtolower($row_content); // 命中目标关键词的属性行 if ( strpos($lower_content, 'oppervlakte') !== false || strpos($lower_content, 'perceel') !== false || strpos($lower_content, 'golf') !== false ) { // 取相邻下一行作为对应数值 $matched_value = $clean_rows[$row_index + 1] ?? '暂未填写'; // 错配校验:如果下一行也是属性标签,说明无对应数值 $next_is_attr = false; if (isset($clean_rows[$row_index + 1])) { $next_lower = strtolower($clean_rows[$row_index + 1]); $next_is_attr = ( strpos($next_lower, 'oppervlakte') !== false || strpos($next_lower, 'perceel') !== false || strpos($next_lower, 'golf') !== false ); } if ($next_is_attr) { $matched_value = '暂未填写'; } // 写入配对结果 $paired_result[$row_content] = $matched_value; } } }
逻辑运行效果
以提供的原始文本样例为例,清洗后的连续数组结构为:
- 索引0:
Bebouwde oppervlakte - 索引1:
80 M2 - 索引2:
Terras oppervlakte - 索引3:
20 M2 - 索引4:
Keuken oppervlakte - 索引5:
12 M2
最终生成的$paired_result键值对为:
Bebouwde oppervlakte=>80 M2Terras oppervlakte=>20 M2Keuken oppervlakte=>12 M2
该结构可直接在任意需要展示的位置调用,实现属性与对应数值的绑定输出。同时加入的错配校验可避免排版异常导致的内容串位问题,适配原始XML的固定结构,不需要修改外部导入的原始内容。
内容的提问来源于stack exchange,提问作者Mark dG
相关产品推荐
相关产品推荐

