PHP 替换多个单词

PHP replace multiple words

所以我想删除除了一些单词以外的所有内容。我想保留 "car"、"circle" 和 "roof" 作为示例。但是删除字符串中的所有其他内容。

假设字符串是 "I have a car with red one circle at the roof"。我想删除除 "car"、"circle" 和 "roof".

以外的所有内容

我知道有这个:

$text = preg_replace('/\bHello\b/', 'NEW', $text);

但我不知道如何用多个单词来完成。我在下面做了这个,但它恰恰相反。

$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 将等于 car circle roof.

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

为了可重用性,你可以创建这样一个函数:

function selector($text,$selected){
$output=explode(' ',$text);

foreach($output as $word){
if (in_array($word,$selected)){
$out[]= trim($word);
}
}
return $out;
}

你得到一个这样的数组:

echo implode(' ',selector($post,$connectors));

我建议 str_word_count() 函数:

<?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);