php-llm-agent/lib/ExtractCodeSections.function.php
Frederico @ VilaRosa02 2e01e34278 init
2025-09-09 10:06:07 +00:00

34 lines
936 B
PHP

<?php
function ExtractCodeSections(string $raw_output) {
$output = [];
$currentBlock = "";
$currentBlockLang = "";
foreach(explode("\n",$raw_output) as $line) {
if (substr($line,0,3) == "```") {
if (empty($currentBlockLang)) {
if (!empty($currentBlock)) {$output[] = trim($currentBlock); $currentBlock = "";}
$currentBlockLang = str_replace("```","",$line) ?? "code";
continue;
} else {
if (isset($output[$currentBlockLang]) && is_string($output[$currentBlockLang])) $output[$currentBlockLang] = [$output[$currentBlockLang]];
if (isset($output[$currentBlockLang]) && is_array($output[$currentBlockLang]))
$output[$currentBlockLang][] = trim($currentBlock);
else
$output[$currentBlockLang] = trim($currentBlock);
$currentBlock = "";
$currentBlockLang = "";
continue;
}
}
$currentBlock .= $line."\n";
}
$output[] = trim($currentBlock);
return $output;
}