Sunday, November 29, 2009

PHP Recursive Strings

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:

[code lang="php"]<?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
?>[/code]

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!

5 comments:

  1. 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]}"
    );

    ReplyDelete
  2. 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.

    ReplyDelete
  3. I am continually invstigating online for tips that can facilitate me. Thx!

    ReplyDelete
  4. An impressive share, I just given this onto a colleague who was doing a little analysis on this. And he in fact bought me breakfast because I found it for him.. smile. So let me reword that: Thnx for the treat! But yeah Thnkx for spending the time to discuss this, I feel strongly about it and love reading more on this topic. If possible, as you become expertise, would you mind updating your blog with more details? It is highly helpful for me. Big thumb up for this blog post!

    ReplyDelete