Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Pinyin Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require overtrue/pinyin
    

    No additional configuration is required—just autoload the package.

  2. First Use Case Convert a single Chinese string to Hanyu Pinyin:

    use Overtrue\Pinyin\Pinyin;
    
    $pinyin = new Pinyin();
    $result = $pinyin->convert('你好世界'); // Returns: 'ni hao shi jie'
    
  3. Where to Look First

    • Documentation (if available)
    • Overtrue\Pinyin\Pinyin class methods:
      • convert() – Basic conversion.
      • convertFirstChar() – Convert only the first character.
      • convertFirstCharToLower() – First character lowercase.
    • Default config (none; uses built-in dictionary).

Implementation Patterns

Common Workflows

  1. Basic Conversion

    $pinyin = new Pinyin();
    $pinyin->convert('Laravel'); // 'la ra vel' (handles mixed scripts)
    
  2. Batch Processing

    $names = ['张三', '李四', '王五'];
    $pinyinNames = collect($names)->map(fn($name) => $pinyin->convert($name));
    // ['zhang san', 'li si', 'wang wu']
    
  3. URL/Slug Generation

    $slug = Str::slug($pinyin->convert('我的博客'), '-');
    // 'wo-de-bo-ke'
    
  4. Custom Separators

    $pinyin->convert('hello世界', '_'); // 'hello_shi_jie'
    
  5. Integration with Eloquent

    // Add a mutator to a User model
    public function setPinyinAttribute()
    {
        $this->attributes['pinyin'] = app(Pinyin::class)->convert($this->name);
    }
    

Advanced Patterns

  • Dictionary Overrides

    $pinyin = new Pinyin();
    $pinyin->setDictionary(['张三' => 'zhangsan']); // Custom mapping
    
  • Performance Optimization For bulk operations, cache results:

    $cache = new Cache();
    $pinyin->convertCached('input', function() use ($cache) {
        return $cache->remember('pinyin:input', now()->addHour(), fn() =>
            app(Pinyin::class)->convert('input')
        );
    });
    
  • Localization Use convertFirstChar() for acronyms (e.g., '张三' → 'Z' for initials).


Gotchas and Tips

Pitfalls

  1. Dictionary Limitations

    • The package relies on a built-in dictionary. Rare names/terms may return incorrect results.
    • Fix: Extend the dictionary via setDictionary() or submit PRs to the repo.
  2. Performance with Large Inputs

    • Converting long strings (e.g., paragraphs) can be slow.
    • Fix: Cache results or process in chunks.
  3. Mixed Scripts

    • Non-Chinese characters (e.g., numbers, symbols) are ignored by default.
    • Fix: Pre-process input to isolate Chinese characters:
      preg_match_all('/[\p{Han}]/u', $input, $matches);
      $pinyin->convert(implode('', $matches[0]));
      
  4. Case Sensitivity

    • Output is lowercase by default. Use convertFirstCharToLower() for mixed-case needs.
  5. Dependency Conflicts

    • Rarely, conflicts may arise with other packages using Overtrue\Pinyin.
    • Fix: Use fully qualified class names or aliases.

Debugging Tips

  • Verify Input Log the input string to ensure it contains Chinese characters:

    dd(mb_strlen($input, 'UTF-8'), mb_strlen($pinyin->convert($input), 'UTF-8'));
    
  • Check Dictionary Inspect the loaded dictionary:

    $pinyin->getDictionary()->get('张三'); // Returns 'zhang san'
    
  • Fallback for Missing Terms Handle undefined terms gracefully:

    try {
        $result = $pinyin->convert('未知词');
    } catch (\Overtrue\Pinyin\Exception\NotSupportException $e) {
        $result = 'unknown';
    }
    

Extension Points

  1. Custom Rules Override the Pinyin class to add logic (e.g., skip certain characters):

    class CustomPinyin extends \Overtrue\Pinyin\Pinyin {
        protected function shouldSkip($char) {
            return parent::shouldSkip($char) || $char === '的';
        }
    }
    
  2. Event Hooks Extend the package by listening to conversion events (if supported in future versions).

  3. Testing Mock the Pinyin class for unit tests:

    $mock = Mockery::mock(Pinyin::class)->shouldReceive('convert')->andReturn('test');
    $this->app->instance(Pinyin::class, $mock);
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager