php比较字符串返回不常见的值?

时间:2012-12-12 06:39:17

标签: php mysql

我发现了一些在php字符串之间返回常用值的好方法(通过explode& array_intersect等),但到目前为止还没有多少用于返回不常见的值。

我找到了一个解决不常见值的问题,the solution使用了array_diff& array_merge。我无法看到实际值,以满足我的需求。

我正在使用遗留数据库,围绕它构建了足够的代码,以使正确的规范化成为一个梦想,并且非常感谢任何见解。

我在mysql数据库表中有两列,一个&湾列a的数据在b中重复,并用空格分隔它们。我需要在b中选择/查询/公开非重复数据。它们之间有一个空间,但它不是唯一的一个,这让我疯狂,因为爆炸/内爆不会削减它(或者我不知道如何实现它)。

现有:

苹果,苹果蓝,苹果红大

b 苹果橘子,苹果蓝香蕉,苹果红大红宝石红葡萄柚

我需要: 橘子,香蕉,红宝石红葡萄柚

有什么想法吗?

3 个答案:

答案 0 :(得分:0)

根据您的示例列值和上面的结果,我假设您只需要比较同一索引处的值。 Apples Apples Oranges Apples Blue Apples Blue Bananas Apples Red Big Apples Red Big Ruby Red Grapefruit ,因为您不希望输出 Blue Bananas 或<强> Red Big Ruby Red Grapefruit

所以你可以尝试这样的事情:

$non_duplicates = array();
foreach($columnA as $idx => $val) {
    $pos = strstr($columnB[$idx], $val);

    if($pos !== false)
        $non_duplicates[] = str_replace($val . " ", "", $columnB[$idx]);
}

var_dump($non_duplicates);

答案 1 :(得分:0)

这应该是你想要的......

$a = 'Apples, Apples Blue, Apples Red Big';
$b = 'Apples Oranges, Apples Blue Bananas, Apples Red Big Ruby Red Grapefruit';

$diff = array_diff(toArray($b), toArray($a)); //diff between b and a
var_dump($diff);

function toArray($str){
  $str = trim(str_replace(array(',','  '), array('',' '), $str));  //clean string up
  return array_unique(explode(' ', $str));  //explode into array by spaces and make unique.
}

<强>输出:

array(4){[1] =&gt; string(7)“Oranges”[4] =&gt; string(7)“Bananas”[8] =&gt; string(4)“Ruby”[10] =&gt; string(10)“Grapefruit”}

答案 2 :(得分:0)

更新:我发现在php.net上使用strstr()可以实现这个技巧(在下面使用)。 链接:http://php.net/manual/en/function.strstr.php 提供者:root at mantoru dot de

$needle = 'Apples Red Big';
$haystack = 'Apples Red Big Ruby Red Grapefruit';

function strstr_after($haystack, $needle, $case_insensitive = false) {
$strpos = ($case_insensitive) ? 'stripos' : 'strpos';
$pos = $strpos($haystack, $needle);
if (is_int($pos)) {
    return substr($haystack, $pos + strlen($needle));
}
// Most likely false or null
return $pos;
}

$goal = strstr_after($haystack, $needle);
echo $goal;

返回:Ruby Red Grapefruit

相关问题