soundex

soundex(string $string): string

Soundex 语音编码:按发音把姓名映射为「字母 + 3 位数字」四字符码,读音相近的名字同码——老派而有效的模糊姓名检索。

C C23

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

/* PHP 变体(Knuth 版):元音与 h/w 同权重置运行码。
   表:a e h i o u w y 为 0,其余按辅音组给数字 */
static const char table[26] = {
    0,'1','2','3',0,'1','2',0,0,'2','2','4','5','5',
    0,'1','2','6','2','3',0,'1',0,'2',0,'2'
};

static void soundex(const char *s, char out[5]) {
    int n = 0, last = -1;
    for (; *s && n < 4; s++) {
        int c = toupper((unsigned char)*s);
        if (c < 'A' || c > 'Z') continue;
        if (n == 0) {
            out[n++] = (char)c;
            last = table[c - 'A'];
        } else {
            int code = table[c - 'A'];
            if (code != last) {
                if (code != 0) out[n++] = (char)code;
                last = code;
            }
        }
    }
    while (n < 4) out[n++] = '0';
    out[n] = '\0';
}

int main(void) {
    char r1[5], r2[5], r3[5], r4[5];
    soundex("Robert", r1); soundex("Rupert", r2);
    soundex("Ashcraft", r3); soundex("Tymczak", r4);
    printf("%s %s\n%s %s\n", r1, r2, r3, r4);
    return 0;
}
输出
R163 R163
A226 T522

C++ C++26

C++26
#include <cctype>
#include <iostream>
#include <string>

// PHP 变体(Knuth 版):元音与 h/w 同权重置运行码
static const char table[26] = {
    0,'1','2','3',0,'1','2',0,0,'2','2','4','5','5',
    0,'1','2','6','2','3',0,'1',0,'2',0,'2'
};

static std::string soundex(const std::string& s) {
    std::string out;
    int last = -1;
    for (char raw : s) {
        if (out.size() >= 4) break;
        int c = std::toupper(static_cast<unsigned char>(raw));
        if (c < 'A' || c > 'Z') continue;
        int code = table[c - 'A'];
        if (out.empty()) {
            out.push_back(static_cast<char>(c));
            last = code;
        } else if (code != last) {
            if (code != 0) out.push_back(static_cast<char>(code));
            last = code;
        }
    }
    return out + std::string(4 - out.size(), '0');
}

int main() {
    std::cout << soundex("Robert") << " " << soundex("Rupert") << "\n";
    std::cout << soundex("Ashcraft") << " " << soundex("Tymczak") << "\n";
    return 0;
}
输出
R163 R163
A226 T522

C# v11.0.100

v11.0.100
using System.Text;

class MainClass {
    // PHP 变体(Knuth 版):元音与 h/w 同权重置运行码
    static readonly int[] Table = {
        0,1,2,3,0,1,2,0,0,2,2,4,5,5,
        0,1,2,6,2,3,0,1,0,2,0,2
    };

    static string Soundex(string s) {
        var outp = new StringBuilder();
        int last = -1;
        foreach (char raw in s.ToUpperInvariant()) {
            if (outp.Length >= 4) break;
            if (raw < 'A' || raw > 'Z') continue;
            int code = Table[raw - 'A'];
            if (outp.Length == 0) {
                outp.Append(raw);
                last = code;
            } else if (code != last) {
                if (code != 0) outp.Append((char)('0' + code));
                last = code;
            }
        }
        return outp.ToString().PadRight(4, '0');
    }

    static void Main() {
        System.Console.WriteLine(Soundex("Robert") + " " + Soundex("Rupert"));
        System.Console.WriteLine(Soundex("Ashcraft") + " " + Soundex("Tymczak"));
    }
}
输出
R163 R163
A226 T522

Go v1.27.4

v1.27.4
package main

import "fmt"

// PHP 变体(Knuth 版):元音与 h/w 同权重置运行码
var table = [26]int{0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0, 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2}

func soundex(s string) string {
	out := make([]rune, 0, 4)
	last := -1
	for _, raw := range s {
		if len(out) >= 4 {
			break
		}
		c := raw
		if c >= 'a' && c <= 'z' {
			c -= 32
		}
		if c < 'A' || c > 'Z' {
			continue
		}
		code := table[c-'A']
		if len(out) == 0 {
			out = append(out, c)
			last = code
		} else if code != last {
			if code != 0 {
				out = append(out, rune('0'+code))
			}
			last = code
		}
	}
	for len(out) < 4 {
		out = append(out, '0')
	}
	return string(out)
}

func main() {
	fmt.Println(soundex("Robert"), soundex("Rupert"))
	fmt.Println(soundex("Ashcraft"), soundex("Tymczak"))
}
输出
R163 R163
A226 T522

Java v27.0.1

v27.0.1
class Main {
    // PHP 变体(Knuth 版):元音与 h/w 同权重置运行码
    static final int[] TABLE = {
        0,1,2,3,0,1,2,0,0,2,2,4,5,5,
        0,1,2,6,2,3,0,1,0,2,0,2
    };

    static String soundex(String s) {
        StringBuilder out = new StringBuilder();
        int last = -1;
        for (char raw : s.toUpperCase().toCharArray()) {
            if (out.length() >= 4) break;
            if (raw < 'A' || raw > 'Z') continue;
            int code = TABLE[raw - 'A'];
            if (out.length() == 0) {
                out.append(raw);
                last = code;
            } else if (code != last) {
                if (code != 0) out.append((char) ('0' + code));
                last = code;
            }
        }
        while (out.length() < 4) out.append('0');
        return out.toString();
    }

    public static void main(String[] args) {
        System.out.println(soundex("Robert") + " " + soundex("Rupert"));
        System.out.println(soundex("Ashcraft") + " " + soundex("Tymczak"));
    }
}
输出
R163 R163
A226 T522

JavaScript v26.13.1

v26.13.1
// PHP 变体(Knuth 版):元音与 h/w 同权重置运行码
const TABLE = [0,1,2,3,0,1,2,0,0,2,2,4,5,5,0,1,2,6,2,3,0,1,0,2,0,2];

function soundex(s) {
  let out = "";
  let last = -1;
  for (const raw of s.toUpperCase()) {
    if (out.length >= 4) break;
    if (raw < "A" || raw > "Z") continue;
    const code = TABLE[raw.charCodeAt(0) - 65];
    if (out.length === 0) {
      out += raw;
      last = code;
    } else if (code !== last) {
      if (code !== 0) out += String(code);
      last = code;
    }
  }
  return (out + "000").slice(0, 4);
}

console.log(soundex("Robert"), soundex("Rupert"));
console.log(soundex("Ashcraft"), soundex("Tymczak"));
输出
R163 R163
A226 T522

PHP v8.6.0

v8.6.0
// PHP 用 Knuth 变体:元音与 h/w 同权重置运行码
// (NARA 标准给 Ashcraft 算 A261——PHP 给 A226,sc 不折叠)
echo soundex("Robert"), " ", soundex("Rupert"), "\n";   // 同码:R163
echo soundex("Ashcraft"), " ", soundex("Ashcroft"), "\n"; // A226 A226
echo soundex("Tymczak"), " ", soundex("Honeyman"), "\n"; // T522 H555
输出
R163 R163
A226 A226
T522 H555

Python v3.15.2

v3.15.2
# PHP 变体(Knuth 版):元音与 h/w 同权重置运行码
TABLE = [0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5,
         0, 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2]


def soundex(s):
    out = ""
    last = -1
    for raw in s.upper():
        if len(out) >= 4:
            break
        if not ("A" <= raw <= "Z"):
            continue
        code = TABLE[ord(raw) - 65]
        if not out:
            out += raw
            last = code
        elif code != last:
            if code != 0:
                out += str(code)
            last = code
    return (out + "000")[:4]


print(soundex("Robert"), soundex("Rupert"))
print(soundex("Ashcraft"), soundex("Tymczak"))
输出
R163 R163
A226 T522

Rust v1.99.1

v1.99.1
// PHP 变体(Knuth 版):元音与 h/w 同权重置运行码
const TABLE: [u8; 26] = [
    0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0, 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2,
];

fn soundex(s: &str) -> String {
    let mut out = String::new();
    let mut last: i32 = -1;
    for raw in s.to_uppercase().chars() {
        if out.len() >= 4 {
            break;
        }
        if !raw.is_ascii_uppercase() {
            continue;
        }
        let code = TABLE[(raw as usize) - 'A' as usize] as i32;
        if out.is_empty() {
            out.push(raw);
            last = code;
        } else if code != last {
            if code != 0 {
                out.push((b'0' + code as u8) as char);
            }
            last = code;
        }
    }
    format!("{:0<4}", out)
}

fn main() {
    println!("{} {}", soundex("Robert"), soundex("Rupert"));
    println!("{} {}", soundex("Ashcraft"), soundex("Tymczak"));
}
输出
R163 R163
A226 T522

TypeScript v26.13.1

v26.13.1
// PHP 变体(Knuth 版):元音与 h/w 同权重置运行码
const TABLE: number[] = [0,1,2,3,0,1,2,0,0,2,2,4,5,5,0,1,2,6,2,3,0,1,0,2,0,2];

function soundex(s: string): string {
  let out = "";
  let last = -1;
  for (const raw of s.toUpperCase()) {
    if (out.length >= 4) break;
    if (raw < "A" || raw > "Z") continue;
    const code = TABLE[raw.charCodeAt(0) - 65];
    if (out.length === 0) {
      out += raw;
      last = code;
    } else if (code !== last) {
      if (code !== 0) out += String(code);
      last = code;
    }
  }
  return (out + "000").slice(0, 4);
}

console.log(soundex("Robert"), soundex("Rupert"));
console.log(soundex("Ashcraft"), soundex("Tymczak"));
输出
R163 R163
A226 T522

语言差异说明

C:26 项编码表 + 手写状态机(示例);注意 toupper 收 unsigned char、out 数组留 \0 位(5 字节);非字母字符完全跳过(不更新 last)——这是 Knuth 原始实现的关键细节。

C++:std::string 版本状态机(示例);凑满 4 字符立即 break(PHP 源码行为:_small < 4 是循环条件,满 4 后的字符不影响结果)。

C#:StringBuilder + PadRight(示例);ToUpperInvariant() 而非 ToUpper()——编码只关心 ASCII 字母,区域无关更稳。

Go:rune 扫描 + 大写偏移 - 32(示例);Go 无内建 soundex——MySQL 的 SOUNDEX() SQL 函数是 Go 服务里最常见的替代路径。

Java:toCharArray 遍历(示例);Apache Commons Codec 有 Soundex 类但那是 NARA 标准版——对 Ashcraft 给 A261,与本示例(复刻 PHP)不同!跨库对表要选对算法。

JavaScript:字符串状态机(示例);charCodeAt(0) - 65 是 A→0 的标准手法;(out + "000").slice(0, 4) 补齐截断一步到位。

PHP:源码是 Knuth TAOCP vol3 版(本机实测四例:Robert/Rupert=R163、Ashcraft/Ashcroft=A226、Tymczak=T522、Honeyman=H555);与 NARA 美国普查局标准的著名分歧:NARA 对 Ashcraft 给 A261(s 与 c 之间隔 h 不折叠)而 PHP 给 A226(h/w 与元音同权重置)——数据库 SOUNDEX() 与 PHP soundex() 可能不同码,跨系统对表必查;空串返回空字符串(非四码)。

Python:手写实现(示例);标准库无 soundex——fuzzy/jellyfish 等 PyPI 包有但多为 NARA 版;自实现 Knuth 版是与 PHP 对表的最稳路径。

Rust:format!("{:0<4}") 左填充补零(示例);无内建 soundex,crates 同样以 NARA 版为主;is_ascii_uppercase 比范围比较更表意。

TypeScript:同 JS(示例);TABLE: number[] 显式类型;建议同时导出 NARA 版以备对表——两种变体共存是 soundex 生态的真实现状。