I found that php preg_replace doesn’t work with HTML tag.
Let’s say I have such a code:
$language = $this->cms_language();
$pattern = array();
$pattern[] = "/\{\{ if_language:$language \}\}(.*)\{\{ elif_language:.*\{\{ end_if }}/";
$pattern[] = "/\{\{ if_language:$language \}\}(.*)\{\{ else \}\}.*\{\{ end_if }}/";
$pattern[] = "/\{\{ if_language:.*\{\{ elif_language:$language \}\}(.*)\{\{ elif_language:.*\{\{ end_if }}/";
$pattern[] = "/\{\{ if_language:.*\{\{ elif_language:$language \}\}(.*)\{\{ else \}\}.*\{\{ end_if }}/";
$pattern[] = "/\{\{ if_language:.*\{\{ else \}\}(.*)\{\{ end_if }}/";
$replacement = '$1';
$value = preg_replace($pattern, $replacement, $value);
$this->cms_language() will return one of “english”, “german” or “indonesia”
When I assign such a string to $value, it will give either “Victoria”, “Hitler” or “Sule” depend on the $language’s value:
$value = '{{ if_language:english }}Victoria{{ elif_language:german }}Hitler{{ else }}Sule{{ end_if }}</p>'
But it won’t work when I change $value into
$value = '{{ if_language:english }}<br />
Victoria<br />
{{ elif_language:german }}<br />
Hitler<br />
{{ else }}<br />
Sule<br />
{{ end_if }}</p>'
The will give $value itself as the output.
So what’s wrong here?
EDIT : Sorry I found this one works:
$value = '{{ if_language:english }}<br />Victoria<br />{{ elif_language:german }}<br /> Hitler<br />{{ else }}<br />Sule<br />{{ end_if }}';
So I guess the problem is with new line character, not with the <br /> tag
The problem is that you’re missing the right pattern modifier.
In this case you should use the
/smodifier, e.g.:The
/smodifier changes how dot.matches characters; by default it matches everything except newlines, but with/sit truly matches anything.Btw, you may want to also use
/Umodifier to make the expression(.*)non-greedy by default; greedy patterns will try to match as much as possible and you may get unexpected results if you use them.Multiple pattern modifiers are specified like this:
Btw, instead of the
/Umodifier you can also use(.*?)to specify non-greedy matching.