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

Name Parser Laravel Package

theiconic/name-parser

Language-independent PHP name parser that splits full names into parts like salutation, first/middle name, initials, nicknames, last name (incl. prefixes like von/de) and suffixes (Jr/III/PhD). Supports comma formats, multi-language rules, and customizable normalization/whitespace.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require theiconic/name-parser
    

    No additional configuration is required—just autoload the package.

  2. First Use Case Parse a name string into structured components, including support for combined initials (e.g., TJ Hooker):

    use TheIconic\NameParser\NameParser;
    
    $parser = new NameParser();
    $result = $parser->parse('TJ Hooker');
    
    // Outputs structured data:
    // [
    //   'first_name' => 'TJ',  // Now correctly parsed as combined initials
    //   'middle_name' => null,
    //   'last_name' => 'Hooker',
    //   'suffix' => null,
    //   'prefix' => null,
    //   'full_name' => 'TJ Hooker'
    // ]
    
  3. Where to Look First

    • Class Docs: NameParser class methods (parse(), parseWithOptions()).
    • Default Rules: Inspect NameParser::DEFAULT_RULES for built-in heuristics (e.g., suffixes like "Jr.", prefixes like "Dr.").
    • Tests: Check the package’s test suite for edge cases, including combined initials (e.g., T.J. Hooker, TJ Smith).

Implementation Patterns

Core Workflows

  1. Basic Parsing (Including Combined Initials)

    $parser = new NameParser();
    $nameData = $parser->parse('TJ Hooker'); // Now correctly parsed as 'TJ'
    $nameData = $parser->parse('T.J. Smith'); // Also handles explicit dots
    
  2. Custom Rules Override default rules for domain-specific needs:

    $customRules = [
        'prefixes' => ['Prof.', 'Rev.'],
        'suffixes' => ['PhD', 'MD'],
    ];
    $parser = new NameParser($customRules);
    $result = $parser->parse('Prof. TJ Garcia PhD');
    
  3. Integration with Laravel

    • Form Request Validation:
      use Illuminate\Validation\Rule;
      
      $validator->after(function ($validator) {
          $name = $validator->getData()['name'];
          $parser = new NameParser();
          $parsed = $parser->parse($name);
          $validator->errors()->merge([
              'name' => [
                  Rule::required()->message('Name is required.'),
                  Rule::string()->message('Name must be a string.'),
              ],
          ]);
      });
      
    • Eloquent Model Casting:
      protected $casts = [
          'full_name' => NameParser::class,
      ];
      
  4. Batch Processing Parse arrays of names efficiently, including combined initials:

    $names = ['Alice', 'TJ Hooker', 'T.J. Smith', 'Bob Jr.'];
    $parser = new NameParser();
    $results = array_map([$parser, 'parse'], $names);
    

Advanced Patterns

  • Handling Combined Initials with Dots The parser now supports both TJ Hooker and T.J. Hooker formats seamlessly.
  • Localization: Extend for non-Latin scripts by subclassing NameParser and overriding parse().
  • Fallback Logic: Combine with other libraries (e.g., league/address) for robustness in edge cases.

Gotchas and Tips

Pitfalls

  1. Combined Initials Misclassification

    • Previously, TJ Hooker might have been parsed as Tj Hooker (incorrectly splitting TJ).
    • Fix: The new version now correctly identifies combined initials (e.g., TJ, LL, DJ). No action required unless you relied on the old behavior.
  2. Performance with Large Datasets

    • Parsing thousands of names sequentially can still be slow.
    • Fix: Use parallel processing (e.g., Laravel queues) or cache results.
  3. Edge Cases with Combined Initials

    • Names like TJJ Hooker or TJJJ Smith may still require validation.
    • Tip: Add custom validation logic if needed:
      if (strlen($parsed['first_name']) > 3 && ctype_alpha($parsed['first_name'])) {
          throw new \InvalidArgumentException('First name may be too long or invalid.');
      }
      

Debugging Tips

  • Inspect Rules: Dump the parser’s rules to debug misclassifications:
    var_dump($parser->getRules());
    
  • Log Parsed Output: Compare expected vs. actual results for combined initials:
    \Log::debug('Parsed name:', $parsedData);
    

Extension Points

  1. Custom Parsers for Combined Initials Extend NameParser to enforce stricter rules for combined initials:

    class StrictNameParser extends NameParser {
        public function parse($name) {
            $result = parent::parse($name);
            if (strlen($result['first_name']) > 3 && !str_contains($result['first_name'], '.')) {
                throw new \RuntimeException('First name too long without dots.');
            }
            return $result;
        }
    }
    
  2. Plugin System for Dynamic Rules Dynamically add rules at runtime, including combined initials validation:

    $parser = new NameParser();
    $parser->addRule('combined_initials', ['TJ', 'LL', 'DJ']); // Whitelist known valid pairs
    
  3. Integration with Laravel Services Bind the parser to the container for dependency injection:

    $this->app->singleton(NameParser::class, function ($app) {
        return new NameParser($app['config']['name_parser.rules']);
    });
    
  4. Handling Mixed Formats Normalize combined initials before processing:

    $normalizedName = str_replace(['.', ' '], '', $name); // Convert "T.J. Hooker" to "TJHooker"
    $parser->parse($normalizedName);
    
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle