difference between two strings

拥有回忆 提交于 2019-12-11 05:37:43

问题


$first = 1,2,3,4,5;
$second = 1,3,5,6;

I need to get difference of those two, so that result would be like:
$result = 2,4,6;


回答1:


Assuming you mean

$first = "1,2,3,4,5";
$second = "1,3,5,6";

then try

$first_array = explode(",", $first);
$second_array = explode(",", $second);
$result_array = array_merge(array_diff($first_array, $second_array), array_diff($second_array, $first_array));
$result = implode("," $result_array);



回答2:


try this:

implode(',',array_diff(explode(',',$first),explode(',',$second)));

EDIT:

updated to fully diff (found on PHP.net and modified):

$first = explode(',', $first);
$second = explode(',', $second);
echo implode(',',array_diff(array_merge($first, $second), array_intersect($first, $second)));



回答3:


first, i'll assume that your strings are properly quoted as strings:

$first = "1,2,3,4,5";
$second = "1,3,5,6";
$diff_string = array_diff(explode(",", $first), explode(",", $second));
$diff_array = implode(",", $diff_string);


来源:https://stackoverflow.com/questions/9692914/difference-between-two-strings

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!