区分字符串

时间:2013-09-02 08:43:26

标签: php arrays diff

我有一个小脚本的例子:

这两个字符串,我想得到不同的数字

$first = "|x|67|x|194|x|113|x|6|x|";
$second = "|x|194|x|113|x|6|x|109|x|";

爆炸他们,获得纯数字

$first_array = explode("|x|", $first);
$second_array = explode("|x|", $second);

获得差异

$result_array = array_merge(array_diff($first_array, $second_array), array_diff($second_array, $first_array));

查看结果

$result = implode(",", $result_array);

我的问题是:

如何获取添加的号码以及从第一个字符串中删除的号码?

3 个答案:

答案 0 :(得分:0)

<?PHP
$first = "|x|67|x|194|x|113|x|6|x|";
$second = "|x|194|x|113|x|6|x|109|x|";

$first_array = explode("|x|", $first);
$second_array = explode("|x|", $second);

$not_in_first_array = array();
$not_in_second_array = array();

foreach( $first_array as $a )
{
    if( ! in_array( $a , $second_array ) )
    {
        $not_in_second_array[] = $a;
    }
}

foreach( $second_array as $a )
{
    if( ! in_array( $a , $first_array ) )
    {
        $not_in_first_array[] = $a;
    }
}

print_r( $not_in_second_array );
print_r( $not_in_first_array );
?>

答案 1 :(得分:0)

您可以尝试以下方法:

<?PHP
$first = "|x|67|x|194|x|113|x|6|x|";
$second = "|x|194|x|113|x|6|x|109|x|";

$first_array = explode("|x|", $first);
$second_array = explode("|x|", $second);

// Get all the values
$allValues = array_filter(array_merge($first_array, $second_array));

// All values which ware the same in the first en second array, and will be removed
$removedValues= array_intersect($first_array, $second_array);

// All new values from the second array
$newValues = array_diff($second_array, $first_array);

答案 2 :(得分:0)

//Removed from first string
$removed_from_first_string = array_diff($first_array, $result_array);
print_r($removed_from_first_string);

//Added from second string
$added_from_second_string = array_diff($second_array, $removed_from_first_string);
print_r($added_from_second_string);