php - How to split text in array by comma if comma is in text value

245

Solution:

Try this

$str = '0, "Some, text", 0.23, 4';
$new = str_getcsv($str, ",","",",");
echo "<pre>";
print_r($new);

Output

Array
(
    [0] => 0
    [1] => Some, text
    [2] => 0.23
    [3] => 4
)

For more info aboutstr_getcsv please read http://php.net/manual/en/function.str-getcsv.php

25

Answer

Solution:

If you use explode for this, the first impresion is that you will indeed get 5 values instead of 4 as you wish.

Your best option would be to usestr_getcsv (link). Check this thread.

194

Answer

Solution:

The simplest way is, by using explode:

$text = "Some, Text";

$parts = explode(", ", $text);
$var1 = array_pop($parts);
$var2 = implode(" ", $parts);

echo "str1: $var1\n";
echo "str2: $var2\n";

Will return "str1: Text str2: Some "

People are also looking for solutions to the problem: php - preg_replace_callback with array

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.