phpstringcsvdelimiter

Replace delimiters in a csv-formatted string containing spaces as delimiters


How can I add a slash or ; after every string.

This is what I have

"SKU" "TITLE" "LINK" "LINK2" "PRICE" "World of Warcraft"

But I will have like that

"SKU";"TITLE";"LINK";"LINK2";"PRICE";"World of Warcraft"

How can I make this? My data source is not in my control -- it comes from an external .txt file.

How can I change the delimiters? I already tried to add ; after every 2nd ", but that didn't work with my code. I also tried with str_replace()

str_replace(" ", ";", $item);

Solution

  • The solution using preg_replace function:

    $str = '"61926182767182" "DAS GEILE GAME" "HTTP://google.com/123129182691239" "HTTP://google.com/123129182691239" "32.59"';
    $str = preg_replace("/(\"[^\"]+\")\s/", "$1;", $str);
    
    print_r($str);  // '"61926182767182";"DAS GEILE GAME";"HTTP://google.com/123129182691239";"HTTP://google.com/123129182691239";"32.59"'
    

    (this approach can be easily extended if there would be tabs instead of spaces in the input string OR if there may be multiple spaces between words. It's more flexible)