PHP替换多个单词

时间:2015-05-05 13:36:54

标签: php words

所以除了一些话,我想删除所有内容。我想留一个例子" car"," circle"和"屋顶"。但是删除字符串中的其他所有内容。

让我们说字符串是"我在车顶上有一个带红色圆圈的汽车"。我想删除所有东西,但" car"," circle"和"屋顶"。

我知道有这个:

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

但我无法弄清楚如何用多个单词做到这一点。我在下面做了这个,但事实正好相反。

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

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

echo $output;

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

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