WP_Text_Diff_Renderer_Table::compute_string_distance() WordPress Method

The WP_Text_Diff_Renderer_Table::compute_string_distance() method is used to calculate the Levenshtein distance between two strings. This is done by first creating an empty grid, where the first row and column represent the length of each string. Then, for each character in string 1, we compare it to each character in string 2. If the characters match, we add 0 to the current cell. If the characters don't match, we take the minimum of the values in the cells to the left, to the right, and above the current cell, and add 1. The Levenshtein distance is the value in the bottom right cell of the grid.

WP_Text_Diff_Renderer_Table::compute_string_distance( string $string1, string $string2 ) #

Computes a number that is intended to reflect the “distance” between two strings.


Parameters

$string1

(string)(Required)

$string2

(string)(Required)


Top ↑

Return

(int)


Top ↑

Source

File: wp-includes/class-wp-text-diff-renderer-table.php

	public function compute_string_distance( $string1, $string2 ) {
		// Use an md5 hash of the strings for a count cache, as it's fast to generate, and collisions aren't a concern.
		$count_key1 = md5( $string1 );
		$count_key2 = md5( $string2 );

		// Cache vectors containing character frequency for all chars in each string.
		if ( ! isset( $this->count_cache[ $count_key1 ] ) ) {
			$this->count_cache[ $count_key1 ] = count_chars( $string1 );
		}
		if ( ! isset( $this->count_cache[ $count_key2 ] ) ) {
			$this->count_cache[ $count_key2 ] = count_chars( $string2 );
		}

		$chars1 = $this->count_cache[ $count_key1 ];
		$chars2 = $this->count_cache[ $count_key2 ];

		$difference_key = md5( implode( ',', $chars1 ) . ':' . implode( ',', $chars2 ) );
		if ( ! isset( $this->difference_cache[ $difference_key ] ) ) {
			// L1-norm of difference vector.
			$this->difference_cache[ $difference_key ] = array_sum( array_map( array( $this, 'difference' ), $chars1, $chars2 ) );
		}

		$difference = $this->difference_cache[ $difference_key ];

		// $string1 has zero length? Odd. Give huge penalty by not dividing.
		if ( ! $string1 ) {
			return $difference;
		}

		// Return distance per character (of string1).
		return $difference / strlen( $string1 );
	}


Top ↑

Changelog

Changelog
VersionDescription
2.6.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.