【问题标题】:PHP replace tags with dynamic values including IF conditionPHP用动态值替换标签,包括IF条件
【发布时间】:2015-06-01 14:34:50
【问题描述】:

在 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


【解决方案1】:

为什么不尝试这样的事情:

<?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。假设您有一个包含 100 个项目的数组,那么这将是不可能的。任何其他解决方案都会很棒。
  • @user96675 您应该首先提供更多详细信息。
【解决方案2】:

首先替换空字符串中的所有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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-09
    • 2013-05-24
    • 2013-03-04
    相关资源
    最近更新 更多