Split into two parts when it contains more delimiter in string with explode

Asked

Viewed 872 times

6

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

3 answers

7


The explode is configured to divide the string by spaces, its string is clearly full of 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 whatever language you come to program, in this case http://php.net/manual/en/function.explode.php:

Returns a string array, each as string substring formed by dividing it from the delimiter.

See how the explosion works:

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

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

<?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 will divide the string into at most 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
)
  • 3

    Good answer, another one of the series, parameters you never remember that there are +1 :D

6

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

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

Returns: Pasteurizado, Mucuri, Integral, 1 L

0

I decided, I created a special string and blew it up.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.