You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PHP中构建包含字母及带重音等特殊字符的正则表达式?

Hey there! Let's work through this regex together since you're just getting started—no stress, we'll build something that fits all your multilingual full name needs perfectly.

The Regex Pattern You Need

First, here's the final pattern that covers every case you listed:

^[\p{L}\d -]+$

Breaking It Down (So You Understand Each Part)

Let's unpack what each piece does, since knowing the "why" helps when you need to tweak it later:

  • ^ and $: These anchor the pattern to the start and end of the string. That means it will only match a full name (not just a part of one buried in other text).
  • [\p{L}\d -]: This is our character set—all the characters we're allowing:
    • \p{L}: The magic part! This matches any Unicode letter, which includes every accented character you mentioned (À, Á, Â, etc.), plus ñ, Ç, ß, and all other multilingual letter variants. No need to list every single accented character manually—this covers them all.
    • \d: Matches any digit (0-9). If you only need Arabic numerals, you can swap this for [0-9] to be extra precise.
    • : A regular space, since you want to allow spaces between first/last names (or middle names).
    • -: The short dash you specified, for hyphenated names like "Jean-Luc" or "Mary-Ann".
  • +: This means "match the preceding character set one or more times"—so we don't end up matching empty strings (which wouldn't be a valid name anyway).

Important Notes for Usage

  • Unicode Support: Make sure your regex engine supports Unicode property classes (\p{L}). Most modern languages (Python 3+, JavaScript with the u flag, Java, C#, etc.) do this by default or with a simple setting. For example, in JavaScript you'd use it like:
    const nameRegex = /^[\p{L}\d -]+$/u;
    
  • If Unicode Isn't Supported: If you're stuck with an older engine that doesn't recognize \p{L}, you can manually expand the character set to include all the accented characters you need. It's more tedious, but here's a truncated example:
    ^[A-Za-zÀ-ÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ\d -]+$
    
    But honestly, the \p{L} version is way cleaner and future-proof.
  • Testing: Always test with your actual name data! Try cases like "José María López", "Hans Müller", "Anne-Claire 123 Dupont" to make sure it works as expected.

Example Matches & Non-Matches

✅ Will match:

  • "Jordi Huertas"
  • "Marie-Élodie Dupont"
  • "José García"
  • "Anna 456 Smith"
  • "Jean-Luc Picard"

❌ Won't match (contains invalid characters):

  • "John@Doe"
  • "Alice!Smith"
  • "Bob#Brown"

内容的提问来源于stack exchange,提问作者Jordi Huertas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 04:18:45