【问题标题】:Patch a string with an unified diff in PHP用 PHP 中的统一差异修补字符串
【发布时间】:2014-06-03 14:52:56
【问题描述】:

我正在寻找一种方法来修补 PHP 中的字符串,使用现有的统一差异。 xdiff_string_patch 完全符合我的要求,但我的服务器上没有 xdiff 库。

有没有办法在普通 PHP 中做到这一点,或者我应该使用类似 shell_exec('patch...') 的东西?

问候,

【问题讨论】:

  • 在我看来,在“香草”PHP 中做到这一点的唯一方法是编写解析差异并应用它的代码(基本上,自己重写 xdiff_string_patch)。所以shell_exec 听起来不错。

标签: php diff patch


【解决方案1】:

这是我最终使用的代码:

/**
 * Applies a diff to a string
 * 
 * @param string $diff Diff
 * @param string $text String to patch
 * 
 * @return string Patched string
 * */
static function applyDiff($diff, $text)
{
    $tmpname = tempnam(sys_get_temp_dir(), "diff");
    $outname = tempnam(sys_get_temp_dir(), "diff");
    $tmp = fopen($tmpname, "w");
    $out = fopen($outname, "r");
    fwrite($tmp, $text.PHP_EOL);
    $proc = proc_open(
        'patch '.$tmpname.' -o '.$outname, array(
           0 => array("pipe", "r"),
           1 => array("pipe", "w"),
           2 => array("pipe", "w")
        ), $pipes
    );
    if (is_resource($proc)) {
        fwrite($pipes[0], $diff);
        fclose($pipes[0]);
        stream_get_contents($pipes[1]);
        $newText = stream_get_contents($out);
        fclose($pipes[1]);
        return $newText;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-17
    相关资源
    最近更新 更多