Pinyin initial search is a common requirement in many Chinese-language applications, especially in scenarios like contact management, product filtering, and content lookup. This article will walk you through implementing such a feature using PHP and a Pinyin conversion library.
The core concept of this search functionality is to take a user-entered keyword, convert it into Pinyin initials, and then match it against preprocessed data to filter relevant entries.
Let’s begin by creating a sample data set — for example, a list of contacts with their names and corresponding Pinyin initials:
$contactList = [
['name' => '张三', 'pinyin' => 'zs'],
['name' => '李四', 'pinyin' => 'ls'],
['name' => '王五', 'pinyin' => 'ww'],
// Additional contacts...
];
You’ll need a library like overtrue/pinyin to convert Chinese characters into Pinyin. Here’s how to load and use it:
require_once 'vendor/autoload.php'; // Load the Pinyin 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));
// Begin search logic
}
After converting the keyword to Pinyin, loop through the contacts list and compare the keyword’s initials with each contact’s:
$results = [];
foreach ($contactList as $contact) {
if (stripos($contact['pinyin'], $keywordPinyin) === 0) {
$results[] = $contact;
}
}
Finally, output the matched contacts on the page:
if (count($results) > 0) {
echo "<ul>";
foreach ($results as $result) {
echo "<li>{$result['name']}</li>";
}
echo "</ul>";
} else {
echo "No matching contacts found.";
}
This article demonstrated how to implement a basic Pinyin initial search in PHP, including setting up the dataset, converting keywords to Pinyin, and filtering based on initials. This approach is useful in any application that needs to handle Chinese-language search features efficiently. With the help of a Pinyin library, you can build a flexible and user-friendly search experience in your PHP projects.