Highlight the difference between two strings in PHP

前端 未结 13 3016
独厮守ぢ
独厮守ぢ 2020-11-22 07:50

What is the easiest way to highlight the difference between two strings in PHP?

I\'m thinking along the lines of the Stack Overflow edit history page, where new text

13条回答
  •  猫巷女王i
    2020-11-22 08:44

    I had terrible trouble with the both the PEAR-based and the simpler alternatives shown. So here's a solution that leverages the Unix diff command (obviously, you have to be on a Unix system or have a working Windows diff command for it to work). Choose your favourite temporary directory, and change the exceptions to return codes if you prefer.

    /**
     * @brief Find the difference between two strings, lines assumed to be separated by "\n|
     * @param $new string The new string
     * @param $old string The old string
     * @return string Human-readable output as produced by the Unix diff command,
     * or "No changes" if the strings are the same.
     * @throws Exception
     */
    public static function diff($new, $old) {
      $tempdir = '/var/somewhere/tmp'; // Your favourite temporary directory
      $oldfile = tempnam($tempdir,'OLD');
      $newfile = tempnam($tempdir,'NEW');
      if (!@file_put_contents($oldfile,$old)) {
        throw new Exception('diff failed to write temporary file: ' . 
             print_r(error_get_last(),true));
      }
      if (!@file_put_contents($newfile,$new)) {
        throw new Exception('diff failed to write temporary file: ' . 
             print_r(error_get_last(),true));
      }
      $answer = array();
      $cmd = "diff $newfile $oldfile";
      exec($cmd, $answer, $retcode);
      unlink($newfile);
      unlink($oldfile);
      if ($retcode != 1) {
        throw new Exception('diff failed with return code ' . $retcode);
      }
      if (empty($answer)) {
        return 'No changes';
      } else {
        return implode("\n", $answer);
      }
    }
    

提交回复
热议问题