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.
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.
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
精彩评论