How to cut a sentence and put the results in strings

Asked

Viewed 51 times

0

how do I split a string (in PHP) from strings I already have, for example:

$frase = 'tem refrigerante na geladeira';
$pergunta = 'tem';
$local = 'na geladeira';

then I wanted him to bring in the $item the word soda.

2 answers

1


You can use a replace:

$frase = 'tem refrigerante na geladeira';
$pergunta = 'tem';
$local = 'na geladeira';

$output  = str_replace($pergunta , "" , $frase);
$output  = str_replace($local , "", $output);

var_dump($output);

//Ou fazer um array e tirar tudo dele
$frase = 'tem refrigerante na geladeira';
$ar = array("na geladeira", "tem");
$output= str_replace($ar , "", $frase);

var_dump($output);

str_replace basically replaces in the string what it finds to be the same as the searched one:

str_replace("o devo procurar?" , "se achar, substituo por isso", "eu procuro aqui");

0

You can use a preg_replace (replace using regex). You’ll get everything you’re in $pergunta and $local and replace the $frase, left over (in this case, refrigerante):

$frase = 'tem refrigerante na geladeira';
$pergunta = 'tem';
$local = 'na geladeira';

$item = trim(preg_replace("/$pergunta|$local/", "", $frase));

echo $item; // retorna -> refrigerante

Check it out at Ideone

Browser other questions tagged

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