simple one really, i’ve written a regular expression to find and replace tags with php constants from within a html snippet. my solution, which works, just doesn’t feel right. how can this be improved?
preg_match_all('/\{CONSTANT_(.*)\}/', $final, $result, PREG_PATTERN_ORDER);
for ($i = 0; $i < count($result[1]); $i++) {
$final = str_replace($result[0][$i], constant($result[1][$i]),$final);
}
You can do it all in one hit with preg_replace_callback
Note I’ve made the
.*non greedy with.*?, this will have the effect of ensuring it doesn’t go eating a } if a longer match is possible. You could get the same effect with([^}]*), or better yet,([a-zA-Z0-9_]+)