0

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?

3 Answers 3

2

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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;

1 Comment

I like this solution because it just call 2 functions which is non-array functions :) Thank you!
0

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.

1 Comment

Thank you for your response. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.