How to separate words from a string?

5

How do I separate words from this string into separate variables with PHP?

I'd like to do something like this:

$frase = "O + rato + roeu + a + roupa + do + rei + de + roma";

for(i=1; i<=**numero de palavras**; i++)
{
    $palavra + i = //Uma palavra por variável sem o sinal de adição.
}

And I want the final result to look like this - every word in a different variable

var1 = O;
var2 = rato;
var3 = roeu;
var4 = a;
var5 = roupa;
var6 = do;
var7 = rei;
var8 = de;
var9 = roma;
    
asked by anonymous 11.11.2016 / 17:24

2 answers

8

There are several ways but I think the best will be an array with explode :

$frase = "O + rato + roeu + a + roupa + do + rei + de + roma";
$palavras = explode('+', $frase);

Now it has an array, doing print_r($palavras); :

  

Array ([0] => [ 1 ] => mouse [ = 2>] => roeu [3] => a [4] => garment [5] = > of [6] => king [7] = > of [8] = > roma)

You can access any of the words through your index within this array, base 0:

$palavras[0] = ' O ';
$palavras[1] = ' rato ';
...

If you want to rejoin them in a sentence without the addition signs, just do an implode :

$frase = implode('', $palavras); // não coloco espaço no primeiro argumento pois este já existe em cada uma das palavras do nosso array

And it stays:

  

The mouse gnawed at the clothes of the king of Rome

However doing what you asked, using the for loop and having a dynamic variable for each word (in this context I do not recommend) you can do:

$frase = "O + rato + roeu + a + roupa + do + rei + de + roma";
$palavras = explode('+', $frase);
for($i = 0, $count = count($palavras); $i < $count; $i++) {
    $varNum = $i+1;
    ${'var' . $varNum} = $palavras[$i];
}
echo $var1; // O
...
echo $var9; // roma
    
11.11.2016 / 17:33
1

If it is as variable numbered type:

$variavel0 = "valor0";
$variavel1 = "valor1";
...

I would do so:

$frase = "O + rato + roeu + a + roupa + do + rei + de + roma";
$palavras = explode(" + ", $frase);

//com variaveis numeradas

for($x = 0; $x < count($palavras); $x++){

    $valTemp = "\$variavel".$x." = \"".$palavras[$x]."\";";
    eval($valTemp);
    echo $valTemp."</br>";

}

You can then use these variables. Example:

echo $variavel4;
// a saída será: roupa
    
11.11.2016 / 17:42