similar_text

similar_text(string $string1, string $string2, &$percent = null): int

Computes string similarity: returns the number of matching characters, with an optional by-reference percentage (2×matching/(len1+len2)×100); paired with levenshtein as similarity vs edit distance.

C C23

C23
#include <stdio.h>
#include <string.h>

/* longest common subsequence, then PHP's percentage formula:
   pct = 2 * L * 100 / (len1 + len2) */
static int lcs(const char *a, const char *b) {
    int la = (int)strlen(a), lb = (int)strlen(b);
    int dp[16][16] = { { 0 } };
    for (int i = 1; i <= la; i++)
        for (int j = 1; j <= lb; j++)
            dp[i][j] = a[i-1] == b[j-1] ? dp[i-1][j-1] + 1
                                        : (dp[i-1][j] > dp[i][j-1] ? dp[i-1][j] : dp[i][j-1]);
    return dp[la][lb];
}

int main(void) {
    printf("%d\n", lcs("hello", "hallo"));   /* 4 */
    printf("%d\n", lcs("kitten", "mitten")); /* 5 */
    return 0;
}
Output
4
5

C++ C++26

C++26
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

static int lcs(const std::string& a, const std::string& b) {
    std::vector<std::vector<int>> dp(a.size() + 1, std::vector<int>(b.size() + 1, 0));
    for (size_t i = 1; i <= a.size(); i++)
        for (size_t j = 1; j <= b.size(); j++)
            dp[i][j] = a[i-1] == b[j-1] ? dp[i-1][j-1] + 1
                                        : std::max(dp[i-1][j], dp[i][j-1]);
    return dp[a.size()][b.size()];
}

int main() {
    std::cout << lcs("hello", "hallo") << "\n";   // 4
    std::cout << lcs("kitten", "mitten") << "\n"; // 5
    return 0;
}
Output
4
5

C# v11.0.100

v11.0.100
class MainClass {
    static int Lcs(string a, string b) {
        var dp = new int[a.Length + 1, b.Length + 1];
        for (int i = 1; i <= a.Length; i++)
            for (int j = 1; j <= b.Length; j++)
                dp[i, j] = a[i-1] == b[j-1] ? dp[i-1, j-1] + 1
                                            : System.Math.Max(dp[i-1, j], dp[i, j-1]);
        return dp[a.Length, b.Length];
    }

    static void Main() {
        System.Console.WriteLine(Lcs("hello", "hallo"));   // 4
        System.Console.WriteLine(Lcs("kitten", "mitten")); // 5
    }
}
Output
4
5

Go v1.27.4

v1.27.4
package main

import "fmt"

// LCS dynamic programming; PHP's percentage formula is
// pct = 2*L*100/(len1+len2) - identical to difflib's ratio
func lcs(a, b string) int {
	dp := make([][]int, len(a)+1)
	for i := range dp {
		dp[i] = make([]int, len(b)+1)
	}
	for i := 1; i <= len(a); i++ {
		for j := 1; j <= len(b); j++ {
			if a[i-1] == b[j-1] {
				dp[i][j] = dp[i-1][j-1] + 1
			} else if dp[i-1][j] > dp[i][j-1] {
				dp[i][j] = dp[i-1][j]
			} else {
				dp[i][j] = dp[i][j-1]
			}
		}
	}
	return dp[len(a)][len(b)]
}

func main() {
	fmt.Println(lcs("hello", "hallo"))   // 4
	fmt.Println(lcs("kitten", "mitten")) // 5
}
Output
4
5

Java v27.0.1

v27.0.1
class Main {
    static int lcs(String a, String b) {
        int[][] dp = new int[a.length() + 1][b.length() + 1];
        for (int i = 1; i <= a.length(); i++)
            for (int j = 1; j <= b.length(); j++)
                dp[i][j] = a.charAt(i-1) == b.charAt(j-1)
                    ? dp[i-1][j-1] + 1
                    : Math.max(dp[i-1][j], dp[i][j-1]);
        return dp[a.length()][b.length()];
    }

    public static void main(String[] args) {
        System.out.println(lcs("hello", "hallo"));   // 4
        System.out.println(lcs("kitten", "mitten")); // 5
    }
}
Output
4
5

JavaScript v26.13.1

v26.13.1
function lcs(a, b) {
  const dp = Array.from({ length: a.length + 1 }, () =>
    new Array(b.length + 1).fill(0)
  );
  for (let i = 1; i <= a.length; i++)
    for (let j = 1; j <= b.length; j++)
      dp[i][j] = a[i-1] === b[j-1] ? dp[i-1][j-1] + 1 : Math.max(dp[i-1][j], dp[i][j-1]);
  return dp[a.length][b.length];
}

console.log(lcs("hello", "hallo"));   // 4
console.log(lcs("kitten", "mitten")); // 5
Output
4
5

PHP v8.6.0

v8.6.0
// Oliver's algorithm: recursive longest common substring, not LCS
similar_text("hello", "hallo", $p);
echo similar_text("hello", "hallo"), " ", round($p, 2), "\n"; // 4 80
similar_text("kitten", "mitten", $p2);
echo similar_text("kitten", "mitten"), " ", round($p2, 2), "\n"; // 5 83.33
Output
4 80
5 83.33

Python v3.15.2

v3.15.2
from difflib import SequenceMatcher

# SequenceMatcher uses the same ratio formula as PHP's percentage:
# 2*M/(len1+len2). The matching algorithm differs (Ratcliff/Obershelp
# vs PHP's recursive longest-common-substring) - values can diverge.
m = SequenceMatcher(None, "hello", "hallo")
print(m.ratio() * 100)            # 80.0

m2 = SequenceMatcher(None, "kitten", "mitten")
print(round(m2.ratio() * 100, 2)) # 83.33
Output
80.0
83.33

Rust v1.99.1

v1.99.1
fn lcs(a: &str, b: &str) -> usize {
    let a: Vec<char> = a.chars().collect();
    let b: Vec<char> = b.chars().collect();
    let mut dp = vec![vec![0usize; b.len() + 1]; a.len() + 1];
    for i in 1..=a.len() {
        for j in 1..=b.len() {
            dp[i][j] = if a[i-1] == b[j-1] {
                dp[i-1][j-1] + 1
            } else {
                dp[i-1][j].max(dp[i][j-1])
            };
        }
    }
    dp[a.len()][b.len()]
}

fn main() {
    println!("{}", lcs("hello", "hallo")); // 4
    println!("{}", lcs("kitten", "mitten")); // 5
}
Output
4
5

TypeScript v26.13.1

v26.13.1
function lcs(a: string, b: string): number {
  const dp: number[][] = Array.from({ length: a.length + 1 }, () =>
    new Array(b.length + 1).fill(0)
  );
  for (let i = 1; i <= a.length; i++)
    for (let j = 1; j <= b.length; j++)
      dp[i][j] = a[i-1] === b[j-1] ? dp[i-1][j-1] + 1 : Math.max(dp[i-1][j], dp[i][j-1]);
  return dp[a.length][b.length];
}

console.log(lcs("hello", "hallo"));   // 4
console.log(lcs("kitten", "mitten")); // 5
Output
4
5

Language differences

C: fixed-size int dp[16][16] = {{0}} (example, zeroed per the iron rule); in real use malloc by length or cap it; the percentage is plain integer math 2*L*100/(la+lb) (hello/hallo gives 80).

C++: vector<vector<int>> dynamic DP (example); watch size_t underflow (i-1 when i is 0) - looping from 1 avoids it; std::max needs <algorithm>.

C#: rectangular array syntax dp[i, j] (example); isomorphic to the levenshtein entry - swapping min for max and the +1-on-mismatch for +1-on-match is the entire difference between the two algorithms.

Go: slice DP (example); PHP's pct formula and Python difflib's ratio are literally the same formula (2M/T), a nice cross-language check; Go has no built-in similarity - hand-written LCS/Levenshtein is standard.

Java: classic two-dimensional DP (example); charAt is O(1); no built-in similarity in the JDK - Apache Commons Lang's StringUtils.getSimilarity (Levenshtein family) is the ecosystem favorite.

JavaScript: Array.from + fill to build the table (example); remember new Array(n).fill(0) before use (the sparse-array map trap); like PHP there is no built-in - npm packages (natural) or hand-writing.

PHP: the algorithm is Oliver's 1993 recursive longest common SUBSTRING (noted in the example) - not textbook LCS; matching-char count plus a by-reference percentage (formula 2*count/(len1+len2)*100; hello/hallo measured 4/80, kitten/mitten 5/83.33); pairs with the A16 levenshtein entry: similarity counts what matches, distance counts the cost; O(len1*len2) recursion depth is a stack risk on long strings.

Python: difflib.SequenceMatcher.ratio() (example) shares PHP's percentage formula and matches on these cases - but the algorithm (Ratcliff/Obershelp longest-matching-block recursion) differs from PHP's Oliver, values CAN diverge on other strings, never assume cross-language equality; get_matching_blocks() exposes the aligned blocks.

Rust: vec! DP table (example); chars() iterates code points, Unicode-safe; no built-in similarity - crates (strsim) provide Jaro/Levenshtein families.

TypeScript: same as JS (example); number[][] typed explicitly; wrapping it in a utility with a complexity note is wise in production - O(len1*len2) is dangerous on long strings.