使用以下代码可以实现替换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时,它不应该显示文本本身。对于这种情况,这是总金额不应该显示为0。
检查If条件不是一个很好的解决方案,因为如果有很多'0'会弄乱代码。
如果有大约100个数组元素,则无法检查每个值。任何可用于任何数据输入的解决方案都会很棒。
任何有想法实现这一目标的人。
感谢。
答案 0 :(得分:1)
为什么不尝试这样的事情:
type
如果总金额为0,它只会删除最后一部分。
根据编辑问题:
my_object = type('my_object', (), {}) # this doesn't work right, it inherits from object
my_type = type('my_type', (my_object,), {})
my_object.__class__ = my_type # this doesn't work at all (it will raise an exception)
答案 1 :(得分:0)
首先从空字符串中替换所有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);