views:

279

answers:

1

Trying to create a simple text-translator in PHP.

It shoult match something like:

Bla bla {translator id="TEST" language="de"/}

The language can be optional

Blabla <translator id="TEST"/>

Here is the code:

$result = preg_replace_callback(
  '#{translator(\s+(?\'attribute\'\w+)="(?\'value\'\w+)")+/}#i',
  array($this, 'translateTextCallback'), 
  $aText
);

It extracts the "attributes", but fetches only the last one. My first thought was, it has to do with the group naming, when PHP overwrites the (named) array elements on every match. But leaving out the group naming it also only returns the last match.

Here is an array as returned to the callback as example

Array
(
    [0] => {translator id="TEST" language="de"/}
    [1] =>  language="de"
    [attribute] => language
    [2] => language
    [value] => de
    [3] => de
)

Any idea what is going wrong?

Thanks

A: 

When you iterate a group, you only get the last match. There's no way around this. You need to match the whole set of attribute/values and then parse them in code.

Jeremy Stein