String Functions

PHP metaphone() Function

Topic: PHP String ReferencePrev|Next

Description

The metaphone() function calculates the metaphone key of a string.

Metaphone key is a short string that represent English pronunciation of a word.

The following table summarizes the technical details of this function.

Return Value: Returns the metaphone key as a string.
Changelog: Since PHP 8.0.0, this function returns FALSE on failure.
Version: PHP 4+

Syntax

The basic syntax of the metaphone() function is given with:

metaphone(string, length);

The following example shows the metaphone() function in action.

<?php
// Sample string
$str = "Hello";

// Calculating metaphone key
echo metaphone($str); // Outputs: HL
?>

Tip: The metaphone() function creates the same key for similar sounding words, similar to soundex(). But, it is more accurate than soundex() as it knows the basic rules of English pronunciation. Also, the generated metaphone keys are variable in length.


Parameters

The metaphone() function accepts the following parameters.

Parameter Description
string Required. Specifies the input string.
length

Optional. Specifies the maximum length of the metaphone key. However, the resulting key length may be slightly longer than the value specified.

The default value is 0 which means, there is no restriction on length.

More Examples

Here're some more examples showing how metaphone() function actually works:

The following example demonstrates the use of this function on similar sounding words:

<?php
// Sample strings
$str1 = "Desert";
$str2 = "Dessert";

// Calculating metaphone key
echo metaphone($str1); // Outputs: TSRT
echo metaphone($str2); // Outputs: TSRT
?>

The following example demonstrates the use of length parameter.

<?php
echo metaphone("programming", 5); // Outputs: PRKRM
echo metaphone("programmer", 5);  // Outputs: PRKRM
echo metaphone("Asterix", 5);     // Outputs: ASTRKS (6 characters metaphone key, instead of 5)
?>
Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties