Voting

: five plus four?
(Example: nine)

The Note You're Voting On

Onyxagargaryll
14 years ago
Here's an approach to create a multidimensional array according to a string's delimiters, i.e. we want to analyze...

"some text (aaa(b(c1)(c2)d)e)(test) more text"

... as multidimensional layers.

<?php
$string
= "some text (aaa(b(c1)(c2)d)e)(test) more text";

/*
* Analyses the string multidimensionally by its opening and closing delimiters
*/
function recursiveSplit($string, $layer) {
preg_match_all("/\((([^()]*|(?R))*)\)/",$string,$matches);
// iterate thru matches and continue recursive split
if (count($matches) > 1) {
for (
$i = 0; $i < count($matches[1]); $i++) {
if (
is_string($matches[1][$i])) {
if (
strlen($matches[1][$i]) > 0) {
echo
"<pre>Layer ".$layer.": ".$matches[1][$i]."</pre><br />";
recursiveSplit($matches[1][$i], $layer + 1);
}
}
}
}
}

recursiveSplit($string, 0);

/*

Output:

Layer 0: aaa(b(c1)(c2)d)e

Layer 1: b(c1)(c2)d

Layer 2: c1

Layer 2: c2

Layer 0: test
*/
?>

<< Back to user notes page

To Top