PHP code example of tekintian / pinyin

1. Go to this page and download the library: Download tekintian/pinyin library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

tekintian / pinyin example snippets


use tekintian\pinyin\PinyinConverter;

// 创建实例
$pinyinConverter = new PinyinConverter();

// 基本转换
$pinyin = $pinyinConverter->convert('你好,世界!');
echo $pinyin; // 输出: ni hao shi jie

// 保留声调
$pinyinWithTone = $pinyinConverter->convert('你好,世界!', ' ', true);
echo $pinyinWithTone; // 输出: nǐ hǎo shì jiè

// 生成URL Slug
$slug = $pinyinConverter->getUrlSlug('你好,世界!');
echo $slug; // 输出: ni-hao-shi-jie

use tekintian\pinyin\unicode\UnihanDataManager;

$manager = new UnihanDataManager();

// 更新Unihan数据
$updated = $manager->updateData();

// 生成数据报告
$report = $manager->generateReport();

// keep模式:保留所有特殊字符
$result = $converter->convert('你好$世界', ' ', false, 'keep');

// delete模式:删除非安全字符
$result = $converter->convert('你好$世界', ' ', false, 'delete');

// replace模式:自定义替换
$result = $converter->convert('你好$世界', ' ', false, [
    'mode' => 'replace',
    'map' => ['$' => 'dollar']
]);

$config = [
    'dict' => [
        // 字典文件路径配置
    ],
    'dict_loading' => [
        'strategy' => 'both',        // 字典加载策略
        'lazy_loading' => true,    // 懒加载开关
        'preload_priority' => ['custom', 'common'], // 预加载优先级
    ],
    'custom_dict_persistence' => [
        'enable' => true,           // 自定义字典持久化
        'delay_write' => true,      // 延迟写入
        'auto_save_interval' => 300  // 自动保存间隔(秒)
    ]
];

$pinyinConverter = new PinyinConverter($config);
bash
# 快速测试
php tools/quick_pinyin_test.php

# 通过Composer运行测试
composer test