PHP正则表达式中的UTF-8 [英] UTF-8 in PHP regular expressions

查看:78
本文介绍了PHP正则表达式中的UTF-8的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要有关正则表达式的帮助.我的字符串包含Unicode字符,下面的代码不起作用.

I need help with regular expressions. My string contains unicode characters and code below doesn't work.

前四个字符必须是数字,然后是逗号,然后是任何字母字符或空格... 我已经读过,如果我在常规表达式末尾添加/u,但对我来说不起作用...

First four characters must be numbers, then comma and then any alphabetic characters or whitespaces... I already read that if i add /u on end of regular expresion but it didn't work for me...

我的代码适用于非unicode字符

My code works with non-unicode characters

$post = '9999,škofja loka';;
echo preg_match('/^[0-9]{4},[\s]*[a-zA-Z]+', $post);

感谢您的回答!

推荐答案

更新后的答案:
现在,它已经过测试并且可以正常工作

Updated answer:
This is now tested and working

$post = '9999, škofja loka';
echo preg_match('/^\\d{4},[\\s\\p{L}]+$/u', $post);

\\w将不起作用,因为它不包含所有unicode字母,并且除了字母之外还包含[0-9_].

\\w will not work, because it does not contain all unicode letters and contains also [0-9_] additionally to the letters.

重要的也是u修饰符,用于激活unicode模式.

Important is also the u modifier to activate the unicode mode.

如果逗号后可以有字母空格,则应将它们放入同一字符类中,在正则表达式中,逗号后应有0个或多个空格,然后只有字母.

If there can be letters or whitespace after the comma then you should put those into the same character class, in your regex there are 0 or more whitespace after the comma and then there are only letters.

请参见 http://www.regular-expressions.info/php.html 有关php正则表达式的详细信息

See http://www.regular-expressions.info/php.html for php regex details

此处

重要的是还使用字符串边界的末尾$来确保确实验证了完整的字符串,否则它将仅匹配第一个空格,例如忽略其余空格.

Important is also the use of the end of string boundary $ to ensure that really the complete string is verified, otherwise it will match only the first whitespace and ignore the rest for example.

这篇关于PHP正则表达式中的UTF-8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆