PHP替换多个单词

PHP替换多个单词,php,words,Php,Words,所以我想删除所有内容,除了一些单词。我想以“汽车”、“圆圈”和“屋顶”为例。但要把其他的东西一网打尽 假设字符串是“我有一辆车顶有一圈红色的汽车”。我想把除了“汽车”、“圆圈”和“屋顶”以外的所有东西都拿走 我知道有一个: $text = preg_replace('/\bHello\b/', 'NEW', $text); 但我不知道如何用多个词来表达。我在下面做过,但它做的恰恰相反 $post = $_POST['text']; $connectors = array( 'array', '

所以我想删除所有内容,除了一些单词。我想以“汽车”、“圆圈”和“屋顶”为例。但要把其他的东西一网打尽

假设字符串是“我有一辆车顶有一圈红色的汽车”。我想把除了“汽车”、“圆圈”和“屋顶”以外的所有东西都拿走

我知道有一个:

$text = preg_replace('/\bHello\b/', 'NEW', $text);
但我不知道如何用多个词来表达。我在下面做过,但它做的恰恰相反

$post = $_POST['text'];
$connectors = array( 'array', 'php', 'css' );

$output = implode(' ', array_diff(explode(' ', $post), $connectors));

echo $output;

为了可重用性,您可以创建如下函数:

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));
您将得到如下数组:

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));
我建议功能:

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

那么你只想检查一下你的句子中是否有
汽车
圆圈
屋顶
这个词?小心这个
s/car/
会弄坏
监禁
之类的东西。请确保包含单词边界标记,以便只抓取“word”
car
,而不是
3个字母-that-恰巧是-Be-car