- str_replace: documentation ( source)
- preg_replace: documentation ( source)
<?php
/**
* Task 2: Parse the string
*
* Parse the $input string and build object tree that represents this structure:
* https://drive.google.com/file/d/0BwhWcFzxN6_mZ2hkQlhZTnRrMDA/view?usp=sharing
* Use Node class to build the tree and dump it to output
*
* Realize Node::dump() function and use it to output the tree in format:
* A
* B
* C
* C
* C
* B
* C
* C
* A
* B
* B
* C
*/
$input = 'A(B(CCC)B(CC))A(BB(C))';
class Node {
public $letter;
private $items = [];
public function __construct($letter) {
$this->letter = $letter;
}
public function addItem($item) {
$this->items[] = $item;
}
public function dump($level = 0) {
// write your code here...
}
}
function createTree(string $input) {
$jsonInput = $input;
$jsonInput = str_replace(['(', ')'], ['[', ']'], $jsonInput);
$jsonInput = preg_replace('~(\w)\[~', '"${1}":\[', $jsonInput);
echo $jsonInput;
}
createTree($input);