如何将重音字符与 PHP preg 匹配?

发布于 2024-08-19 06:40:58 字数 184 浏览 4 评论 0原文

我想让我的用户不仅可以选择填写字母和数字,还可以选择“特殊”字母,例如“á”、“é”等。但是,我不希望他们能够使用符号像“!”,“@”,“%”等。

有没有办法编写正则表达式来完成此任务?(最好不指定每个特殊字母。)

现在我有:

$reg = '/^[\w\-]*$/';

I’d like to give my users the option to not only fill in letters and numbers, but also “special” letters like the “á”, “é”, etc. However, I do not want them to be able to use symbols like “!”, “@”, "%”, etc.

Is there a way to write a regex to accomplish this? (Preferably without specifying each special letter.)

Now I have:

$reg = '/^[\w\-]*$/';

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

当梦初醒 2024-08-26 06:40:58

您可以使用 Unicode 字符属性 来描述字符:

/^[\p{L}-]*$/u

\ p{L} 描述 Unicode 字母字符的类别。

You could use Unicode character properties to describe the characters:

/^[\p{L}-]*$/u

\p{L} describes the class of Unicode letter characters.

汐鸠 2024-08-26 06:40:58

哪些字符被视为“单词字符”取决于区域设置。您应该设置一个在其自然字母表中包含这些字符的区域设置,并为正则表达式使用 /u 修饰符,如下所示:

$str = 'perché';
setlocale(LC_ALL, 'it_IT@euro');
echo preg_match('#^\w+$#u', $str);

What characters are considered "word-characters" depends on the locale. You should set a locale which has those characters in its natural alphabet, and use the /u modifier for the regexp, like this:

$str = 'perché';
setlocale(LC_ALL, 'it_IT@euro');
echo preg_match('#^\w+$#u', $str);
吹梦到西洲 2024-08-26 06:40:58

你可以尝试使用这个正则表达式:

$reg = '~[^\\pL\d]+~u';

它也捕获重音字符

you can try with this regex:

$reg = '~[^\\pL\d]+~u';

which catch also accented characters

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文