Split into two parts when it contains more than one delimiter in the exploded string

5
$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 to prod[1] save the entire sting, including the commas, but when I run the explode it does not return the entire string

    
asked by anonymous 12.02.2016 / 20:44

3 answers

7

The explode is set to split the string by spaces, its string is clearly all spaces:

$produto = 'Leite Pasteurizado, Mucuri, Integral, 1 L';

When you run explode , it returns an array like this:

array(
   'Leite', 'Pasteurizado,', 'Mucuri,', 'Integral,', '1', 'L'
);

If you read the documentation you will understand better how php works and whatever language you are programming, in the case link :

  

Returns an array of strings, each as a string substring formed by splitting it from the delimiter.

See how the explode works:

array explode ( string $delimiter , string $string [, int $limit ] )

The optional parameter named $limit can solve your problem, so do:

<?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 the maximum two items in the array, the result will be this:

Leite
Pasteurizado, Mucuri, Integral, 1 L
Array
(
    [0] => Leite
    [1] => Pasteurizado, Mucuri, Integral, 1 L
)
    
14.02.2016 / 03:05
6

You can use the strstr() function to return the one to the right of the string:

echo strstr('Leite Pasteurizado, Mucuri, Integral, 1 L', ' ');

Returns: Pasteurizado, Mucuri, Integral, 1 L

    
12.02.2016 / 20:51
0

I solved, I created a special string and exploded it.

<?php echo $linha['tipo_produto'].'*'.$linha['nome_marca']?>
$prod = explode('*', $produto);
    
12.02.2016 / 20:50