热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

在现有正则表达式中支持空格字符-EnablingSpaceCharactersinCurrentRegularExpressions

本文探讨了在当前正则表达式中支持空格字符的方法。作者尝试在正则表达式中允许空白字符,但遇到了一些问题,导致该表达式无法正确识别空格。文章详细分析了问题的原因,并提出了解决方案,旨在提高正则表达式的灵活性和实用性。

I am trying to allow whites space in my regex. For some reason this expression will not allow white space. Here is my current regex

我试图在我的正则表达式中允许白色空间。由于某种原因,此表达式将不允许空格。这是我现在的正则表达式

preg_match( "/^[A-Za-z0-9?.,-=$@!&%';:)(_\s]+$/", $value )

2 个解决方案

#1


Perhaps the white space you try to match is not in the ascii range. (for example the non-breakable space). So you can try to add the u modifier to extend the \s character class to all the unicode whitespaces (by default \s contains only ascii whitespaces).

您尝试匹配的空白区域可能不在ascii范围内。 (例如不易碎的空间)。因此,您可以尝试添加u修饰符以将\ s字符类扩展为所有unicode空格(默认情况下,仅包含ascii空格)。

So try this:

试试这个:

preg_match( "/^[A-Za-z0-9?.,-=$@!&%';:)(_\s]+$/u", $value )

or this:

preg_match( "/(*UCP)(*UTF8)^[A-Za-z0-9?.,-=$@!&%';:)(_\s]+$/", $value )

Note: I suggest you to perform clever tests to be sure that whitespaces are really the problem. Note2: this pattern matches exactly the same thing, but it uses character ranges (take a look at the ascii table) and the case insensitive modifier i:

注意:我建议你进行巧妙的测试,以确保空白确实是问题所在。注意2:这个模式完全匹配相同的东西,但它使用字符范围(看一下ascii表)和不区分大小写的修饰符i:

preg_match( "/^[!$-'(),-=?@-Z_\s]+$/ui", $value )

#2


It does match whitespace:

它匹配空格:

preg_match("/^[A-Za-z0-9?.,-=$@!&%';:)(_\s]+$/", '   '); // true
preg_match("/^[A-Za-z0-9?.,-=$@!&%';:)(_\s]+$/", 'a a'); // true
preg_match("/^[A-Za-z0-9?.,-=$@!&%';:)(_\s]+$/", 'aaa'); // true
preg_match("/^[A-Za-z0-9?.,-=$@!&%';:)(_\s]+$/", 'a*a'); // false

推荐阅读
author-avatar
捕鱼达人2502856571
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有