php - 比较逗号分隔字符串之间的差异

标签 php string compare

我有 2 个字符串,我想比较差异并使用这些不同项目的值。例如:

$stringA = "1, 2, 3, 4, 5"
$stringB = "1, 2, 4, 5, 6"

所以与 stringB 的区别在于缺少 '3' 并添加了 '6'。

我想执行一个使用值“3”和“6”的函数。为了将其放在上下文中,想象一下在 MySQL 查询中使用字符串,其中我只想更新 id 3 和 6 的记录,因为它们已更改,因此需要更新,但其余部分保持不变,因此无需更新数据库记录那些。我希望这是有道理的?

如何使用 PHP 获取差异并确保结果再次是带有逗号分隔值的字符串?即

$stringDifference = "3, 6"

最佳答案

刚刚在我的机器上运行了代码,这将解决这个问题

$stringA = "1, 2, 3, 4, 5";
$stringB = "1, 2, 4, 5, 6";

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

$Difference_1 = array_diff($stringA, $stringB); // Check string A Against String B
$Difference_2 = array_diff($stringB, $stringA); // Check String B against String A
$Difference = array_merge($Difference_1, $Difference_2); // Merge the two difference arrays together 
$Difference = implode(',', $Difference); // Convert to a string
echo "The Difference Between The Two Is: ".$Difference; // Echo the difference
<小时/>

更新

function Differences ($Arg1, $Arg2){
    $Arg1 = explode (',', $Arg1);
    $Arg2 = explode (',', $Arg2);

    $Difference_1 = array_diff($Arg1, $Arg2);
    $Difference_2 = array_diff($Arg2, $Arg1);
    $Diff = array_merge($Difference_1, $Difference_2);
    $Difference = implode(',', $Diff);
    return "The Difference Between The Two Is: ".$Difference;
}

$stringA = "1, 2, 3, 4, 5";
$stringB = "1, 2, 4, 5, 6";


// Call By:

echo Differences($stringA, $stringB);

抱歉更新延迟。我已经习惯了 PHPStorm 作为新的脚本编辑器。

关于php - 比较逗号分隔字符串之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15696821/

相关文章:

python - 克服 python 中的 appengine 500 字节字符串限制?考虑文本

java - 从 HTML 字符串创建 HTMLDocument(在 Java 中)

c++ - 比较字符串c++的问题

c# - 如何比较不同的 SQL 表并寻找差异?

c# - 在c#中获取字符串之间的字符串

c# - dictionary.TryGetValue 与 FirstOrDefault

php - 如何在 PHP 中实现布隆过滤器?

php - 如何替换 http ://or www with <a href. 。在 PHP 中

php - 在 PHP/MySQL 中获取具有实际列名的列号

php - 在网页上显示加载时执行的 PHP 文件的输出/回显