2

I'm outputting some HTML from a database to a page, containing constructions like this:

<p>Department: *|accounting|*</p>

I would like to find and replace all text wrapped with | and | and use the word in between as a variable for my translate function.

I've found a partial answer. Could you guys help me out with the rest? Thanks.

This is somewhat what I'm looking for...

$html_from_database = "<p>Department: *|accounting|*</p>";

$updated_html = preg_replace("*|(.*?)|*", translate('accounting'),$html_from_database);

Is something like this possible? What about the regex? Is it not too resource intensive or to greedy? Please note that the only characters between | and | will be a-z A-Z -_ 0-9.

Thanks in advance.

Community
  • 1
  • 1
chocolata
  • 3,258
  • 5
  • 31
  • 60

2 Answers2

1

I would do it in two steps, find the matches, then call the translate function on each one and build up the resulting string. Something like this pseudocode:

matches = preg_find(".*(\|([a-zA-Z0-9\-_]*)\|).*", sourceHtml)
foreach match in matches
    outputHtml += sourceHtml(section between previous match and this one)
    outputHtml += translate(inner group from match)
    record end position of match
outputHtml += end of sourceHtml
Don Kirkby
  • 53,582
  • 27
  • 205
  • 286
1

Try this, I just tested it and it works:

preg_match_all('/\|(.*?)\|/', $source, $matches);
foreach($matches[1] as $match) {
    $source = str_replace($match,translate($match),$source);
}

$source is your source text.

Alexander Ivanov
  • 717
  • 4
  • 16
  • Thanks, it works and translates well. Only problem is that $source is still wrapped in *| and |*. How can we tweak it? [edit: the star symbol doesn't display in comments apparently...] – chocolata Apr 13 '11 at 18:16
  • 1
    Use `foreach($matches[1] as $mid => $match) $source = str_replace($matches[0][$mid],translate($match),$source);` instead then. – Alexander Ivanov Apr 13 '11 at 18:22
  • Thanks, man! This works. I just updated the regex a little bit, because you're version doesn't take into account the star symbol (which for some reasons I cannot put in comments...) – chocolata Apr 13 '11 at 19:41