-2

我有这个数组:

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

谢谢!

4

3 回答 3

1

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

$tokens = explode(' ', $string);
$difference = array_diff($tokens, $GivenString);
于 2012-12-25T07:47:31.727 回答
1

我认为简单str_replace会帮助你

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

echo str_replace($GivenString, "", $string);
于 2012-12-25T07:55:44.323 回答
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);
于 2012-12-25T08:24:43.283 回答