PHP将标签替换为动态值,包括IF条件


PHP replace tags with dynamic values including IF condition

可以使用以下代码替换PHP中的动态值:

$replace = array('{COVER_AMT}','{LIABILITY_AMT}','{TOTAL_AMT}');
$with = array('90', '90', '0');
$myString = 'This is Cover Amt : {COVER_AMT} . This is liablity amount :     {LIABILITY_AMT} . This is total amount : {TOTAL_AMT}';
echo str_replace($replace, $with, $myString);
输出:

This is Cover Amt : 90 . This is liablity amount : 90 . This is total amount : 0

这会给出正确的输出。

但是当值为0时,它不应该显示文本本身。在这种情况下,this is total Amount根本不应该显示,因为它是0。

使用If条件检查不是一个很好的解决方案,因为如果有很多' 0 ',它会弄乱代码。

如果有大约100个数组元素,将不可能检查每个值。任何可以用于任意数量数据输入的解决方案都将是伟大的。

任何一个有好主意的人都可以做到这一点。

谢谢。

为什么不试试呢:

<?php
$replace = array('{COVER_AMT}','{LIABILITY_AMT}','{TOTAL_AMT}', 'This is total amount : 0');
$with = array('90', '90', '0','');
$myString = 'This is Cover Amt : {COVER_AMT} . This is liablity amount :     {LIABILITY_AMT} . This is total amount : {TOTAL_AMT}';

echo str_replace($replace, $with, $myString); 
?>

如果总金额为0,则只删除最后一部分。

根据编辑的问题:

<?php
$replace = array('{COVER_AMT}','{LIABILITY_AMT}','{TOTAL_AMT}');
$with = array('0', '90', '0');
$myString = 'This is Cover Amt : {COVER_AMT} . This is liablity amount :     {LIABILITY_AMT} . This is total amount : {TOTAL_AMT}';
$myString = str_replace($replace, $with, $myString);
$myString_array = explode("This is",$myString);
foreach($myString_array as $myString_sliced) { 
$pattern = '/('.?)(This is )(.*?) 0('s?)('.?)/i';
$replacement = '';
if($myString_sliced)
echo preg_replace($pattern, $replacement, "This is ".$myString_sliced);
}
?>

首先从空字符串中替换所有0,试试下面的代码

<?php 
$replace = array('{COVER_AMT}','{LIABILITY_AMT}','{TOTAL_AMT}');
$with = array('90', '90', '0');
$with = array_map(function($v){return $v <= 0 ? '' : $v;}, $with);
$myString = 'This is Cover Amt : {COVER_AMT} . This is liablity amount :     {LIABILITY_AMT} . This is total amount : {TOTAL_AMT}';
echo str_replace($replace, $with, $myString);