PHP:如何获得“无与伦比”的字符串?

时间:2012-12-25 07:44:39

标签: php

我有这个数组:

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

如何获得' unmatch'像这样的变量字符串:

$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 '

谢谢!

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

我认为简单str_replace会帮助你

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

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

答案 2 :(得分: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);