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

问题描述:

我发现了一些很好的方法来返回php字符串之间的常见值(通过爆炸& array_intersect等),但迄今为止没有太多的返回非常规值。PHP的比较字符串返回不常见的值?

我确实发现了一个解决非常见值的问题,the solution使用了array_diff & array_merge。我很难让它看到实际值,以适应我的需求。

我正在使用遗留数据库,并在其周围建立了足够的代码以使适当的规范化成为管道梦想,并将非常感谢任何见解。

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

现有:

一个苹果,苹果蓝,苹果红大

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

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

有什么想法?

+0

我们可以有代码吗? –

+0

你特别想要什么?我试过的所有东西都失败了。请查看表格字段a和字段b的内容,以及上面所需的输出。 – Gary

+0

@Daya,请停止链接到w3schools的PHP材料。它已经过时了,充满了坏习惯和可怕的安全措施。相反,请链接到PHP手册。在字符串函数的情况下,这将[在这里](http://php.net/ref.strings)。 – Charles

更新:我发现了一个在php.net上使用strstr()的技巧(下面使用)。 链接:由http://php.net/manual/en/function.strstr.php 提供:在mantoru根德点

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

返回:宝石红葡萄柚

根据上面的样本列值和结果,我假设您只需要比较同一索引处的值。 ApplesApples OrangesApples BlueApples Blue Bananas,并Apples Red BigApples Red Big Ruby Red Grapefruit,因为你不希望输出如下Blue BananasRed 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); 
+0

嗨SubRed,非常感谢您的建议,并且您的比较假设是正确的 - 每行。我试图实现它,并不断获得'code'array(0){}'code' – Gary

+0

这是我的,请指出我的错误:'code' $ a = $ row_TableA ['a']] ; $ b = $ row_TableA ['b']; $ non_duplicates = array(); \t \t foreach($ a as $ idx => $ val){ \t \t \t $ pos = strstr($ b [$ idx],$ val); \t \t \t \t \t如果($ POS ==假!) \t \t \t \t $ non_duplicates [] = str_replace函数($ VAL “”, “”,$ B [$ IDX]); \t \t} \t \t \t \t的var_dump($ non_duplicates);'code' – Gary

+0

你有没有试过'print_r'你'$了'你的'$ B'?我没有看到这个函数有问题,你应该首先看到这些变量值。 – SubRed

这应该几乎是你在寻找什么......

$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. 
} 

OUTPUT:

阵列(4) {[1] => string(7)“Oranges”[4] => string(7)“Bananas”[8] => string(4)“Ruby”[10] => string(10)“Grapefruit”}

+0

嗨on_,我不能在空间上爆炸,因为在上面所需的结果中有空格。我在你的回复中遗漏了什么? – Gary