views:

41

answers:

3

I have two strings:

$string = shell_exec('reg.bat '.$arg); //returns word\0word\0word
$stringA = "$string";
$stringB = "word,other,word2,other2";
$array1 = explode('\0', $stringA);
$array2 = explode(',', $stringB);
$result = array_diff($array1, $array2);

I can use array_diff to find the differences, but the last word shows up as not in both strings even though it is because of the \0 delimiter.

+1  A: 

Explode the string to an array and have a look at the array_diff function.

zwip
I tried that, but it doesn't compare properly.
John Coder
Try switching the arguments when calling array_diff().
zwip
What if the words aren't in the same order in both strings?
John Coder
+2  A: 

Try:

$stringA = "word,other,word2,other";
$stringB = "word,other,word2,other2";

$array1 = explode(',', $stringA);
$array2 = explode(',', $stringB);

$result = array_diff($array2, $array1);

echo '<pre>';
print_r($result);

Result:

Array
(
    [3] => other2
)

More Info:

Sarfraz
+1  A: 

You can use array_diff and str_word_count:

print_r(
    array_diff(
        str_word_count("word\0word\0word", 1, '0123456789'),
        str_word_count("word,other,word2,other2", 1, '0123456789'))
);
// will return an empty array, because "word" is in "word,other,word2,other2"

Or switch the input around:

print_r(
    array_diff(
        str_word_count("word,other,word2,other2", 1, '0123456789'),
        str_word_count("word\0word\0word", 1, '0123456789'))
);
// will return an array containing "other", "word2", "other"
Gordon
I think I was able to get this to work, but I have another problem.In the first string that I compare, the words are separated by \0 instead of a comma.I used this to add commas, but the string still isn't being processed the same as if I manually typed "word,word,word":$string = str_replace("\\0",",",$string);$string = "$string";How can I format the string with commas and get it to process the same way as $stringB?
John Coder
@John if they are like this `'word\0other\0word2\0other2'` then all you have to change is the quotes so it reads `"word\0other\0word2\0other2"` - with single quotes the strings wont be treated as null characters, but backslash zero.
Gordon
Because of that \0, the array_diff function is outputting the last word in my array even though it is in both strings. What I can do about the last word in word\0word\0word ?
John Coder
@John can you please update the question accordingly, so others have a chance to adjust their codes, too? Also, I dont understand what you are saying. If you use double quotes, the above will output "other2", which is the only word that is not present in both word lists.
Gordon
Updated the question
John Coder