overtrue/pinyin
Convert Chinese characters to Pinyin in PHP/Laravel. overtrue/pinyin supports full pinyin, initials, tone options, segmentation, and custom dictionaries—ideal for search indexing, sorting, slugs, and transliteration in web apps.
Pinyin::useMemoryOptimized() - 切换到内存优化策略Pinyin::useCached() - 切换到缓存策略Pinyin::useSmart() - 切换到智能策略Pinyin::useAutoStrategy() - 自动选择最佳策略Pinyin::clearCache() - 清理所有转换器缓存ConverterFactory::make($strategy) - 创建指定策略的转换器ConverterFactory::recommend() - 获取推荐策略ConverterFactory::getStrategiesInfo() - 获取所有策略信息php benchmark/run.php - 运行性能基准测试php benchmark/compare-strategies.php - 策略对比测试docs/benchmark-guide.md# 运行标准基准测试,显示所有方法的性能表现
php benchmark/run.php
# 详细的策略对比测试,对比三种策略的性能差异
php benchmark/compare-strategies.php
基准测试会显示:
heteronym() 方法(5.3.3+ 引入)继续保持兼容sentence, phrase, chars 等) 保持不变从 5.x 升级到 6.0 非常简单,所有现有代码都能正常工作:
// 5.x 和 6.x 都能正常工作
Pinyin::sentence('你好世界');
// 6.x 默认使用内存优化策略,内存占用更低
// 如果你需要与 5.x 完全相同的高性能(高内存占用)
Pinyin::useCached(); // 一次设置,全局生效
Pinyin::sentence('你好世界');
// 自动选择最佳策略(推荐用于新项目)
Pinyin::useAutoStrategy();
// 或者根据场景手动选择:
// Web 应用(内存受限)
Pinyin::useMemoryOptimized();
// 批处理任务(性能优先)
Pinyin::useCached();
// 通用场景(平衡)
Pinyin::useSmart();
// 监控内存使用
$initialMemory = memory_get_usage();
$result = Pinyin::sentence('测试文本');
$memoryUsed = memory_get_usage() - $initialMemory;
echo "内存使用: " . round($memoryUsed / 1024, 2) . " KB";
// 批处理完成后清理缓存
Pinyin::useCached();
// ... 批量处理 ...
Pinyin::clearCache(); // 释放内存
| 策略 | 内存占用 | 首次转换 | 重复转换 | 推荐场景 |
|---|---|---|---|---|
| Memory Optimized | ~400KB | 中等 | 中等 | Web 请求、内存受限环境 |
| Cached | ~4MB | 慢 | 最快 (2-3x) | 批处理、长时运行进程 |
| Smart | 600KB-1.5MB | 快 | 快 | 通用场景、自动优化 |
基于 1000 次转换的基准测试结果:
| 文本长度 | Memory Optimized | Cached | Smart |
|---|---|---|---|
| 短文本 (<10字) | 1.2ms | 0.5ms | 0.8ms |
| 中等文本 (10-50字) | 3.5ms | 1.2ms | 2.1ms |
| 长文本 (>100字) | 8.7ms | 3.1ms | 5.2ms |
How can I help you explore Laravel packages today?