How to cut a sentence and put the results in strings

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';

I wanted him to bring the word refrigerant into the $ item.

    
asked by anonymous 24.04.2018 / 02:39

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 equal to the searched:

str_replace("o devo procurar?" , "se achar, substituo por isso", "eu procuro aqui");
    
24.04.2018 / 02:47
0

You can use preg_replace ( replace using regex ). It will take everything in $pergunta and $local and make a replace in $frase , remaining what remains (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

See on Ideone

    
24.04.2018 / 05:03