views:

291

answers:

2

I have a group of text based rules that are structured like this:

Rule 1: Do [XXX] when [PN] greater than [N]
Rule 2: Get [PRD ..] and add [X.XX]

To go with this is an array of data that translates each grouped code into a CSS class ID (for jQuery).

I also have an array of translations from [code] to ID stored in a simple structured array, like the following example:

$translate = array(
    'XXX' => 'gen-string-input', 
    'PN' => 'gen-positivenumber-input',
    'N' => 'gen-number-input'
);

It is important that the following can be achieved:

I need to replace each instance of [code] with a span tag that is structured like this:

<span class="[classname]" unique="[hash]" offset="[offset]">[CODE]</span>

This is assuming that the fields are

  • classname is the result of the $translate array
  • hash is an md5 hash that is static for each rule
  • offset is the position of the field in the string (e.g. in the first example, field [XXX] is at position 0, [PN] at position 1 and so on).

Based on this information, I would expect to achieve the following output for Rule 1:

<p>
    Do <span class="gen-string-input" 
             unique="[md5]"
             offset="0">[XXX]</span>
    when <span class="gen-positivenumber-input"
               unique="[md5]" 
               offset="1">[PN]</span>
    greater than <span class="gen-number-input" 
                       unique="[md5]" 
                       offset="2">[N]</span>
</p>

Any help is greatly appreciated, I am currently using str_replace to try and achieve this but it is just not good enough.

A: 

Ok, actually what you need is preg_replace_callback. See the recursive callback examples.

vartec
A: 

Iterate through the translate array, replacing the keys in the string with the values

$string = '[CODE]';
$translate = array('classname' => 'oddRow', 'hash' => 'abcdef');

foreach($translate AS $key=>$value)
{
$string = str_ireplace('[' . $key . ']', $value, $string);
}
adam