Question:
$produto = "Leite Pasteurizado, Mucuri, Integral, 1 L";
$prod = explode(" ", $produto);
$prod[0]; //tipo_produto = Leite
$prod[1]; //marca_produto = Pasteurizado, Mucuri, Integral, 1 L
I need prod[1]
keep the entire sting, including the commas, but when I run the explode it doesn't return the entire string to me
Answer:
The explode
is configured to divide the string by spaces, its string is clearly all spaces:
$produto = 'Leite Pasteurizado, Mucuri, Integral, 1 L';
When the explode
, it returns an array like this:
array(
'Leite', 'Pasteurizado,', 'Mucuri,', 'Integral,', '1', 'L'
);
If you read the documentation, you will better understand how php works and or any other language you might be programming, in this case http://php.net/manual/pt_BR/function.explode.php :
Returns an array of strings, each as a string substring formed by dividing it from the delimiter.
See how explodes works:
array explode ( string $delimiter , string $string [, int $limit ] )
The optional parameter called $limit
might solve your problem, do it like this:
<?php
$produto = 'Leite Pasteurizado, Mucuri, Integral, 1 L';
$prod = explode(' ', $produto, 2);
echo $prod[0], '<br>';
echo $prod[1], '<br>';
print_r($prod);//Visualizar a array
The 2
indicates that it will split the string into a maximum of two items in the array (array), the result will be this:
Leite
Pasteurizado, Mucuri, Integral, 1 L
Array
(
[0] => Leite
[1] => Pasteurizado, Mucuri, Integral, 1 L
)