Current Location: Home> Latest Articles> PHP Tutorial: How to Efficiently Implement Pinyin Initials Search Function

PHP Tutorial: How to Efficiently Implement Pinyin Initials Search Function

M66 2025-06-24

Use Cases for Implementing Pinyin Initials Search with PHP

The pinyin initials search function is commonly used in many applications, especially in contact lists and product searches. This article explains how to implement this function using PHP to help developers easily build a pinyin initials based search system.

Core Concept of Pinyin Initials Search

The key to implementing pinyin initials search is converting the user's search keyword into pinyin initials, then matching these initials with those stored in the data source to filter relevant results.

Preparing the Data Source Example

First, we need a data source, which can be an array or a database table storing contact information. Here's an example contact list with names and their corresponding pinyin initials:
$contactList = [
    ['name' => 'Zhang San', 'pinyin' => 'zs'],
    ['name' => 'Li Si', 'pinyin' => 'ls'],
    ['name' => 'Wang Wu', 'pinyin' => 'ww'],
    // other contacts...
];

Include the Pinyin Conversion Library and Get User Input

After receiving the user's keyword via an input box, use a pinyin conversion library (such as “overtrue/pinyin”) to convert the keyword into pinyin initials, which facilitates subsequent matching.
require_once 'vendor/autoload.php'; // Load pinyin conversion library

use Overtrue\Pinyin\Pinyin;

$pinyin = new Pinyin();
$keyword = isset($_POST['keyword']) ? trim($_POST['keyword']) : '';

if ($keyword) {
    $keywordPinyin = implode('', $pinyin->convert($keyword, Pinyin::DEFAULT_MODE));
    // proceed with search logic...
}

Implement Pinyin Initials Matching Search

Loop through the contact list and check if each contact’s pinyin initials start with the converted keyword initials; if so, add that contact to the results array.
$results = [];

foreach ($contactList as $contact) {
    if (stripos($contact['pinyin'], $keywordPinyin) === 0) {
        $results[] = $contact;
    }
}

Display Search Results

Finally, display the matching contacts to the user. If no matches are found, show an appropriate message.
if (count($results) > 0) {
    echo "<ul>";
    foreach ($results as $result) {
        echo "<li>{$result['name']}</li>";
    }
    echo "</ul>";
} else {
    echo "No matching contacts found";
}

Conclusion

This article explained how to use PHP together with a pinyin conversion library to implement a simple but practical pinyin initials search feature. By converting input keywords into pinyin initials and matching them against the data source, this approach enables fast contact filtering. It is suitable not only for contact search but also for products, articles, and various other search scenarios, greatly improving search experience and efficiency.