Skip to content

Instantly share code, notes, and snippets.

@gnh1201
Created February 15, 2020 19:09
Show Gist options
  • Select an option

  • Save gnh1201/e26a7c42d1c2dec54354227a85b72397 to your computer and use it in GitHub Desktop.

Select an option

Save gnh1201/e26a7c42d1c2dec54354227a85b72397 to your computer and use it in GitHub Desktop.
PHP bracket expression parser (experimental)
<?php
$str = "aaa(b, x(), c(d,e), f(g), h(i(3), j, k(l, n(z(0), 1), m)))";
/*
a->b
a->x
a->c
a->c
a->f
h->i
i->3
h->j
k->l
k->n
n->z
z->0
n->1
k->m
*/
$relations = array();
// step 1
$exps = array();
$chars = str_split($str);
$exp = "";
foreach($chars as $char) {
if(in_array($char, array('(', ')', ','))) {
$exp = trim($exp);
if($exp != '') {
$exps[] = trim($exp);
}
$exp = "";
$exps[] = $char;
} else {
$exp .= $char;
}
}
// step 2
$depth = 0;
$_exps = array();
$_depth = 0;
$_exp = "";
$_v_depth = 0;
$_v_exp = "";
foreach($exps as $exp) {
if($exp == '(') {
$depth++;
array_push($_exps, $_exp);
}
if($exp == ')' && $_exp == '(') {
$__exps = $_exps;
$__exp_A = array_pop($__exps);
$__exp_B = array_pop($__exps);
$relations[] = array($__exp_B, $__exp_A);
}
if($exp == ')') {
$depth--;
array_pop($_exps);
}
// store previous expression
if(!in_array($exp, array('(', ')'))) {
if($_v_depth < $depth) {
$v1 = current($_exps);
while($v1 !== false) {
$v2 = next($_exps);
if($v2 !== false) {
$relations[] = array($v1, $v2);
}
$v1 = $v2;
}
$relations[] = array($_v_exp, $exp);
}
$_v_depth = $depth;
$_v_exp = $exp;
}
$_depth = $depth;
$_exp = $exp;
}
var_dump($relations);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment