How to separate words from a string?

Asked

Viewed 1,196 times

5

How do I separate the words from that string in 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 end result to look like this - each word in a different variable

var1 = O;
var2 = rato;
var3 = roeu;
var4 = a;
var5 = roupa;
var6 = do;
var7 = rei;
var8 = de;
var9 = roma;

2 answers

8

It has 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 have an array, doing print_r($palavras);:

Array ( [0] => O [1] => rat [2] => roeu [3] => a [4] => clothing [5] => do [6] => rei [7] => de [8] => roma )

You can access any of the words via their index within this array, base 0:

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

If you want to put them back together in a sentence without the plus signs just make a 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 rat gnawed on the clothes of the king of rome

However doing what you asked, using the for cycle and having a dynamic variable for each word (in this context do not recommend) 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

1

If as type numbered variable:

$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
  • 1

    Perfect Andrei, thank you very much.

  • Tranquil @abduzeedo... be happy =)

  • Don’t forget to approve the reply @abduzeedo. Hug

Browser other questions tagged

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