w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
PHP Convert 2 strings into binary, compare the differences and save differences

If im understanding correctly, you want to have array_diff() behaviour on two strings, ok then just explode() them into an arrays, there is no need to base2 them before (if the source is base2 then convert it back).

But from your expected output you wont get what you want from array_diff() alone.

Your need to use array_merge() and array_intersect() into array_diff() to return what's different.

Here is the user function:

<?php
function str_diff($stringA='', $stringB='')
{
    $arrayA = explode(' ', $stringA);
    $arrayB = explode(' ', $stringB);

    //What I think you want
    return array_diff(
        array_merge($arrayA, $arrayB),
        array_intersect($arrayA, $arrayB)
    );

    //There's also this, but A has priority over B
    //return array_diff($arrayA, $arrayB);

    //And this returns just all unique, not compared
    //return array_unique(array_merge($arrayA, $arrayB));
}
?>

Example A

<?php
$strA = "PHP are good!";
$strB = "PHP is good man!";

$diff = str_diff($strA, $strB);

/*
Array
(
    [1] => are
    [2] => good!
    [4] => is
    [5] => good
    [6] => man!
)
*/
echo '<pre>'.print_r($diff, true).'</pre>';
//are good! is good man!
echo implode(' ', $diff);
?>

Example B

<?php 
$strA = "PHP are good!";
$strB = "PHP the good!";

$diff = str_diff($strA, $strB);

/*
Array
(
    [1] => are
    [4] => the
)
*/
echo '<pre>'.print_r($diff, true).'</pre>';
//are the
echo implode(' ', $diff);
?>

The saving of the string would be a trivial call to file_put_contents()

Hope it helps.





© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.