Muntashir Are Rahi
Muntashir Are Rahi

Reputation: 43

Break string into specific data using delimiter and store in the array in PHP

I have the following text string

Liane Lanford$310.40$0.00$325.92 Ken Christenson$134.75$0.00$141.49 Melissa Jaramillo$951.78$0.00$999.37

I need to create an array so that i can insert the data into mysql database in the following format

enter image description here

I tried to do it using explode but stacked at Ken Christenson and Melissa Jaramillo. And complexity is there may be 3, 4 five or more customer instead of 3. How can i do this in php.

Upvotes: 1

Views: 59

Answers (1)

Ste Bächler
Ste Bächler

Reputation: 478

you could split it with regex:

preg_match_all('/ ?([^\$]+)(\$[0-9\.,]+)(\$[0-9\.,]+)(\$[0-9\.,]+)/i',$str,$results);

the $results array would contain the full match at index 0, followed by name, subtotal, holdback, total:

[
  [
    "Liane Lanford$310.40$0.00$325.92",
    " Ken Christenson$134.75$0.00$141.49",
    " Melissa Jaramillo$951.78$0.00$999.37"
  ],
  [
    "Liane Lanford",
    "Ken Christenson",
    "Melissa Jaramillo"
  ],
  [
    "$310.40",
    "$134.75",
    "$951.78"
  ],
  [
    "$0.00",
    "$0.00",
    "$0.00"
  ],
  [
    "$325.92",
    "$141.49",
    "$999.37"
  ]
]

for the insert part (that you asked in the comments), try this:

try this instead:

for ($i=0;$i<count($array[0]);$i++) {
    mysqli_query($link, "INSERT INTO table(name,subtotal,holdback,total) VALUES ('" . $array[0][$i] . "','" . $array[1][$i] . "','" . $array[2][$i] . "','" . $array[3][$i] . "') ");
}

but keep in mind that the values should be checked & escaped. if any name contains an ' , the query will fail

Upvotes: 1

Related Questions