Taufik Nur Rahmanda
Taufik Nur Rahmanda

Reputation: 1969

PHP truncate commas in string

in PHP, I want to change this string:

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

into this:

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

I've managed to strip commas at the beginning and end of the string, but this only accomplish 50% of my need:

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

result:

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

Any solution?

Upvotes: 0

Views: 71

Answers (3)

Azeez Kallayi
Azeez Kallayi

Reputation: 2642

You can use trim() and Regx to achieve this, please have a look on the below code, it may help you

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

Upvotes: 1

apokryfos
apokryfos

Reputation: 40700

Do this little trick:

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

If your string is more complicated (i.e. it's a CSV which may potentially have fields wrapped in " " to escape commas you can do this:

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

Where str_putcsv is defined in https://gist.github.com/johanmeiring/2894568 as

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;
    }
}

Upvotes: 2

FatBoyXPC
FatBoyXPC

Reputation: 951

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

That's a little bit to read, but essentially explode the string on a comma, call array_filter on the result of that, then implode it back together.

Upvotes: 0

Related Questions