PHP Recursive Strings

Posted: November 29th, 2009 | Author: Bret Kuhns | Filed under: Programming | Tags: | 2 Comments »

I needed to construct a recursive string of regular expression patterns. Parts of a string may be built from another string which may also be built of other strings. If you’re familiar, think of production rules in a context-free grammar. If you’re not, then just take for granted this recursive string idea would be useful. I initially decided to build all my patterns into a single array, giving me a nice data collection to access them. I was also under the assumption that my recursive idea would work best with an array as the interpreter would have to account for all strings in the array at once. This would prevent order issues if one string relied on another but wasn’t yet declared. Unfortunately, PHP simply doesn’t seem to work as I had hoped.

Consider the following snippet of code:

<?php
$a = array(
     0 => "test {$a[1]}",
     1 => "blah {$a[2]}",
     2 => "argh"
);
echo $a[0]."\n";	// outputs: test

$s2 = "argh";
$s1 = "blah {$s2}";
$s0 = "test {$s1}";

echo $s0."\n";	// outputs: test blah argh
?>

At first, we attempt to use an array to handle the string recursion, then we use string variables.We can see from the output that the array code simply doesn’t work. It appears you can’t access parts of the array from within itself. At the moment, it looks like I’m stuck avoiding arrays for this. If anyone out there knows a way around this, please let me know!


2 Comments on “PHP Recursive Strings”

  1. 1 Noah said at 2:32 pm on January 14th, 2010:

    This is what I would guess is happening:
    1. PHP creates $a.
    2. The initializer creates $a[0]. When it does this, $a[1] has no value since it has not yet been assigned, so “test {$a[1]}” evalulates to just “test “.
    3. Same with $a[1].

    If I’m right, then you can actually use this as you intend, but by doing this:
    $a = array(
    2 => “argh”,
    1 => “blah {$a[2]}”,
    0 => “test {$a[1]}”
    );

  2. 2 Bret Kuhns said at 2:39 pm on January 14th, 2010:

    Hey Noah! I came to the same conclusion and you’re exactly right. That’s how I solved the problem. I guess I should’ve mentioned that here, huh? I must have gotten too used to compiled languages for a while and PHP’s line-by-line interpreting threw me a curve ball here.


Leave a Reply