2012-12-25 44 views
-2

我有這個數組:PHP:如何獲得'不匹配'字符串?

$GivenString = array("world", "earth", "extraordinary world"); 

如何讓 '失配' 的變量,像這樣的字符串:

$string = 'hello, world'; // output = 'hello, ' 
$string = 'down to earth'; // output = 'down to ' 
$string = 'earthquake'; // output = '' 
$string = 'perfect world'; // output = 'perfect ' 
$string = 'I love this extraordinary world'; // output = 'I love this ' 

的感謝!

+2

可以用空字符串替換每個字符串數組中每個出現的單詞。 –

+0

你有什麼試過?什麼都沒有奏效?你已經做了什麼研究來解決這個問題?您是否查看了[string](http://php.net/book.strings)和[array](http://php.net/book.array)函數列表,查看可能有用的東西? – Charles

+0

'unmatch('a b c',array('a b','b c'))''a'或''c''?那麼'array('a b','a b c')'? – irrelephant

回答

1

我想簡單str_replace將幫助您

$GivenString = array("world", "earth", "extraordinary"); 

echo str_replace($GivenString, "", $string); 
1

和array_diff http://php.net/manual/en/function.array-diff.php

$tokens = explode(' ', $string); 
$difference = array_diff($tokens, $GivenString); 
+1

不適用於最後一個示例(即跨多個單詞)。 –

+1

第三個例子呢? '$ string ='earthquake'; //輸出='''? – Engineer

+0

兄弟,是不是array_diff只適用於數組到數組的比較?在我的情況下,它是字符串到數組。 –

0

str_replace不會幫助,因爲有例子$string = 'earthquake'; // output = ''。這裏有一段代碼可以完成你的工作。

$GivenString = array("world", "earth", "extraordinary world"); 

foreach ($GivenString as &$string) { 
    $string = sprintf('%s%s%s', '[^\s]*', preg_quote($string, '/'), '[^\s]*(\s|)'); 
} 

// case sensitive 
$regexp = '/(' . implode('|', $GivenString) . ')/'; 

// case insensitive 
// $regexp = '/(' . implode('|', $GivenString) . ')/i'; 


$string = 'earthquake'; 
echo preg_replace($regexp, '', $string);