- array_shift: documentation ( source)
- explode: documentation ( source)
<?php
class Node
{
private $key, $kids;
public function __construct(string $key, ?Node $parent = null)
{
if ($parent !== null)
$parent->kids[$key] = $this;
$this->key = $key;
}
public function match(array $parts): ?self
{
if (empty($parts))
return $this;
$part = array_shift($parts);
if (isset($this->kids[$part]))
return $this->kids[$part]->match($parts);
else
return null;
}
public function getKey(): string
{
return $this->key;
}
}
/*
* root
* |-- foo
* `-- bar
* `-- baz
*/
$root = new Node("");
$foo = new Node("foo", $root);
$bar = new Node("bar", $root);
$baz = new Node("baz", $bar);
$node = $root->match(explode("/", "bar/baz"));
if ($node !== null)
echo $node->getKey();