I am looking for a way to replace all string looking alike in entire page with their defined values
Please do not recommend me other methods of including language constants.
Strings like this :
[_HOME]
[_NEWS]
all of them are looking the same in [_*] part
Now the big issue is how to scan a HTML page and to replace the defined values .
One ways to parse the html page is to use DOMDocument and then pre_replace() it
but my main problem is writing a pattern for the replacement
$pattern = "/[_i]/";
$replacement= custom_lang("/i/");
$doc = new DOMDocument();
$htmlPage = $doc->loadHTML($html);
preg_replace($pattern, $replacement, $htmlPage);
In RegEx,
[]are operators, so if you use them you need to escape them.Other problem with your expression is
_*which will match Zero or more_. You need to replace it with some meaningful match, Like,_.*which will match _ and any other characters after that. SO your full expression becomes,/\[_.*?\]/Hey, why an
?, you might be tempted to ask: The reason being that it performs a non-greedy match. Like,[_foo] [_bar]is the query string then a greedy match shall return one match and give you the whole of it because your expression is fully valid for the string but a non-greedy match will get you two seperate matches. (More information)You might be better-off in being more constrictive, by having an
_followed by Capital letters. Like,/\[_[A-Z]+\]/Update: Using the matched strings and replacing them. To do so we use the concept called back-refrencing.
Consider modifying the above expression, enclosing the string in parentheses, like,
/\[_([A-Z]+)\]/Now in
preg-replacearguments we can use the expression in parentheses by back-referencing them with$1. So what you can use is,Note: We needed the
e modifierto treat the second parameter as PHP code. (More information)