So I want to remove everything but some words. I want to keep for an example "car", "circle" and "roof". But remove everything else in a string.
Let's say the string is "I have a car with red one circle at the roof". I wantr to remove everything but "car", "circle" and "roof".
I know there's this one:
$text = preg_replace('/\bHello\b/', 'NEW', $text);
But I can't figure out how to do it with multiple words. I've done this below, but it does the opposite.
$post = $_POST['text'];
$connectors = array( 'array', 'php', 'css' );
$output = implode(' ', array_diff(explode(' ', $post), $connectors));
echo $output;
<?php
$wordsToKeep = array('car', 'circle', 'roof');
$text = 'I have a car with red one circle at the roof';
$words = explode(' ', $text);
$filteredWords = array_intersect($words, $wordsToKeep);
$filteredString = implode(' ', $filteredWords);
$filteredString
would then equal car circle roof
.
For the sake of reusability, you can create a function like this:
function selector($text,$selected){
$output=explode(' ',$text);
foreach($output as $word){
if (in_array($word,$selected)){
$out[]= trim($word);
}
}
return $out;
}
You get an array like this:
echo implode(' ',selector($post,$connectors));
I suggest the str_word_count() function:
<?php
$string = "Hello fri3nd, you're
looking good today!
I have a car with red one circle at the roof.
An we can add some more _cool_ stuff :D on the roof";
// words to keep
$wordsKeep = array('car', 'circle', 'roof');
// takes care of most cases like spaces, punctuation, etc.
$wordsAll = str_word_count($string, 2, '\'"0123456789');
// remaining words
$wordsRemaining = array_intersect($wordsAll, $wordsKeep);
// maybe do an array_unique() here if you need
// glue the words back to a string
$result = implode(' ', $wordsRemaining);
var_dump($result);