I am trying to get a variable value and add it in a string to output html elements. Here is my code:
// String
$str = 'Some validations [IF TEST]<a href="text.html">firstValue</a>[ELSEIF TEST1]secondValue[/IF] in [IF OK]thirdValue[/IF] end of string.';
// Regex
$do = preg_match_all("/\[IF (.*?)\](.*?)(\[\/IF\]|\[ELSEIF(.*?)\](.*?)\[\/IF\])/i", $str, $matches, PREG_SET_ORDER);
$str = str_replace("[IF ". $matches[0][1] ."]", "<?php if($". $matches[0][1] ."){ echo('".$matches[0][2]."');} ?>", $str);
echo $str;
However, for some reasons, when I use the $matches[0][2], it breaks my string giving this result in the browser:
Some validations firstValue');} ?>firstValue[ELSEIF TEST1]secondValue[/IF] in [IF OK]thirdValue[/IF] end of string.
and this in the source:
Some validations <?php if($TEST){ echo('<a href="text.html">firstValue</a>');} ?><a href="text.html">firstValue</a>[ELSEIF TEST1]secondValue[/IF] in [IF OK]thirdValue[/IF] end of string.
Thanks all !
PHP is not going to execute the PHP that is inside your string. All you’re doing is replacing
[IF TEST]...with a block of PHP code, which will not get processed. You need to process the PHP code first and then replace the[IF TEST]...section with the result of that code.Try using variable variables to check if the variable
$TESTis set and then insert the appropriate text corresponding to that variable.