PHP在字符串中截断逗号

时间:2017-03-05 07:36:40

标签: php string

在PHP中,我想更改此字符串:

",,,3,4,,,5,6,,7,8,"

进入这个:

"3,4,5,6,7,8"

我设法在字符串的开头和结尾处删除逗号,但这只能满足我50%的需求:

<?php
$hello = ",,,3,4,5,6,,7,8,";
echo rtrim(ltrim($hello,","),",");

结果:

"3,4,,,5,6,,7,8"

任何解决方案?

3 个答案:

答案 0 :(得分:2)

这个小技巧:

$hello = ",,,3,4,,,5,6,,7,8,";
$hello = implode(",",array_filter(explode(',',$hello)));

如果你的字符串更复杂(即它是一个CSV,可能有字段包含在&#34;&#34;以逃脱逗号,你可以这样做:

$hello = ",,,3,4,,,5,6,,\"I,have,commas\",,7,8,";
$fields = array_filter(str_getcsv($hello));
$hello = str_putcsv($fields);

https://gist.github.com/johanmeiring/2894568中将str_putcsv定义为

if (!function_exists('str_putcsv')) {
    function str_putcsv($input, $delimiter = ',', $enclosure = '"') {
        $fp = fopen('php://temp', 'r+b');
        fputcsv($fp, $input, $delimiter, $enclosure);
        rewind($fp);
        $data = rtrim(stream_get_contents($fp), "\n");
        fclose($fp);
        return $data;
    }
}

答案 1 :(得分:1)

您可以使用trim()和Regx实现此目的,请查看以下代码,它可能对您有所帮助

$from = ",,,,,,3,4,,,5,6,,7,8,,,";
echo $from;
echo "<pre>";
$to = preg_replace('/,+/', ',', trim($from,","));
echo $to;

答案 2 :(得分:0)

implode(",", array_filter(explode(",", ",,,3,4,,,5,6,,7,8,"))

这是一点点阅读,但基本上是explode逗号上的字符串,在结果上调用array_filter,然后implode将它重新组合在一起。