Search code examples
phpwords

PHP replace multiple words


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;

Solution

  • <?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.

    See http://php.net/manual/en/function.array-intersect.php