Question

I'm at the moment using PHP but I suppose there are other coding languages that would handle this problem better. If you have any suggestions on other coding languages that might work better, please tell me.

I'm trying to convert a nested text to separate strings. It's kind of hard to explain as English is not my native language so instead I'll write an example of what I'm trying to accomplish.

The source:

foo {
    bar tree;
    bar ball/sand;
    snafu {
        string;
    }
    random {
        nested {
            value;
            bohica;
        }
    }
}

The goal:

foo bar tree
foo bar ball/sand
foo snafu string
foo random nested value
foo random nested bohica

So far, my best attempt:

foreach($curlybrace as $stance){
    $semicolon = explode(';',$string);
    foreach($semicolon as $break){
        $result = 'set ' . $curlybrace[0] . $break .'<br />';
        echo $result . '<br />';
    }
}

In my code above, I tried using several PHP functions like str_replace, trim, preg_replace, preg_split, implode, explode to modify the result by removing the curly braces that are left behind but I was unable to make that work.

All hints and help on how to make this work is very much appreciated.

Was it helpful?

Solution

This snippet here simply goes through the array, char by char. And decides on {, } and , whether to go one step up or down or if the actual string needs to be printed.

$buf = "";
$brace_level = 0;
$words = array();
for ($i = 0; $i < strlen($text); $i++) {
    switch ($text[$i]) {
        case '{':
            $words[$brace_level] = trim($buf);
            $buf = "";
            $brace_level++;
            break;
        case '}':
            unset($words[$brace_level]);
            $brace_level--;
            unset($words[$brace_level]);
            break;
        case ';':
            $words[$brace_level] = trim($buf);
            $buf = "";
            print implode(" ", $words)."\n";
            break;
        default:
            $buf .= $text[$i];
    }
}

Online demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top