I am looking for a way to patch a string in PHP, using an existing unified diff. xdiff_string_patch does exactly what I want but the xdiff library is not available on my server.
Is there a way to do this in vanilla PHP or should I use something like shell_exec('patch...') ?
Regards,
Here is the code I ended up using:
/**
* 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;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.