【问题标题】:Remove comma from string in php从php中的字符串中删除逗号
【发布时间】:2016-08-10 03:46:11
【问题描述】:

假设值为

1,2,,4,5,6 - 为此我可以使用str_replace(",,",",",$mystring) 获取1,2,4,5,6

如何从,2,,4,5,6 中获取2,4,5,6 之类的值,其中两个或多个连续逗号被一个逗号替换,如果逗号在任何值之前,则忽略它。如果只有,,,,,, 之类的逗号,则为空值被退回。

如何在 php 中做到这一点。

【问题讨论】:

  • 试试这个:str_replace(',,', ',', 1,2,,4,5,6);
  • 只是出于好奇,那个字符串是从哪里来的?也许问题在于该字符串是如何创建的。数字之间不能有三个逗号吗?在这种情况下,它只会替换一对逗号并留下两个逗号。
  • 这个逗号分隔值来自具有相同名称的输入框。我使用逗号保存它们的值。如果任何输入为空,则字符串将有一个空的位置,后跟逗号。所以每当我需要预填充这些值我只是运行循环。在预览中我必须只显示实际值。

标签: php


【解决方案1】:

你可以先用逗号explode字符串,过滤空字符串后再implode

$val=",2,,4,5,6";
$parts=explode(",",$val);
$parts=array_filter($parts);
echo(implode(",",$parts));

请注意,这也会从您的值中过滤出0。如果你想保留零,请参考this question

【讨论】:

  • 请注意,array_filter 也可以删除零。我不确定 OP 是否想要零。
【解决方案2】:

你可以做你在第一个问题上所做的......

然后使用trim() 删除字符串前面或结尾处不必要的逗号。

$mystring = ',2,,4,5,6';

$output = str_replace(',,', ',', $mystring);

echo trim($output, ',');

//Output will be: 2,4,5,6

【讨论】:

    【解决方案3】:
    // Variable Declaration for String
    $str = "1,2,,4,5,6";
    
    // Create Array Out of the String, The comma ',' is the delimiter
    // This would output 
    //       [ 1 => 1, 2 => 2, 3 => '', 4 => 4, 5 => 5, 6 => 6 ]
    $explodedStr = explode(',', $str);
    
    // Filter Array And Remove The empty element which in this case
    //    3 => ''
    $filteredArray = array_filter( $explodedStr );
    
    // Convert Array into String with comma delimiter 
    $formattedString = implode(',',  $filteredArray);
    

    【讨论】:

    • 虽然这段代码可能有助于解决问题,但它并没有解释为什么和/或如何回答问题。提供这种额外的背景将显着提高其长期价值。请edit您的答案添加解释,包括适用的限制和假设。
    猜你喜欢
    • 2012-03-09
    • 1970-01-01
    • 2015-07-27
    • 2011-04-24
    • 1970-01-01
    • 2016-04-19
    • 2021-03-21
    • 1970-01-01
    • 2010-09-05
    相关资源
    最近更新 更多