简体   繁体   English

Preg匹配大写和小写用户输入

[英]Preg Match both Upper and Lowercase user Input

I'm working on a shopping cart that has coupons and the owner has told me that the customers seem unwilling to use the proper casing for the issued coupons and are annoying the staff with constant complaints that the coupons don't work. 我正在使用带有优惠券的购物车,店主告诉我,客户似乎不愿意为已发行的优惠券使用合适的包装,并且不断抱怨这些优惠券不起作用,使员工感到烦恼。

I was initially going to simply strtoupper() the user input, but then this would require that the owner use only uppercase coupon codes and that makes no sense. 我最初只是简单地使用strtoupper()用户输入,但是这将要求所有者仅使用大写的优惠券代码,这没有任何意义。

I'd like to do a preg_match() on the user input and simply allow it to match if all the characters are correct and ignore case altogether. 我想在用户输入上执行一个preg_match(),并在所有字符正确且完全忽略大小写的情况下简单地使其匹配。 But alas ... I have NO idea how to work with regex to get what I need. 但是,...。。。我不知道如何使用正则表达式来获取所需的东西。

This what I have now: 这就是我现在所拥有的:

strtoupper ($this->request->post['coupon'])

and as I said this works great against an uppercase coupon code from the db but forces the owner to uppercase all their codes. 就像我说的那样,这对数据库中的大写优惠券代码非常有效,但会强制所有者将其所有代码大写。

Any help would be greatly appreciated. 任何帮助将不胜感激。

-V -V

Simply convert both to the same case and compare: 只需将它们都转换为相同的大小写并进行比较:

if(strtolower($input) == strtolower($check))

Even better, use strcasecmp() to do a binary safe case-insensitive string comparison: 更好的是,使用strcasecmp()进行二进制安全的不区分大小写的字符串比较:

if (strcasecmp($input, $check) == 0)

It depends on how you check the coupon codes. 这取决于您如何检查优惠券代码。 If you're running a database query, SQL and friends allow you to perform a case-insensitive query. 如果您正在运行数据库查询,则SQL和好友允许您执行不区分大小写的查询。 If you're comparing them one-by-one against eg a configuration file, then instead of saying if (code_entered === valid_code) , say if (strtolower(code_entered) === strtolower(valid_code)) . 如果要与例如配置文件一一比较,则不要说if (code_entered === valid_code) ,而要说if (strtolower(code_entered) === strtolower(valid_code)) Otherwise, we'll need to know how the actual comparison is happening, as that's the important part. 否则,我们将需要知道实际比较是如何进行的,因为这是重要的部分。

"this would require that the owner use only uppercase coupon codes and that makes no sense." “这将要求所有者仅使用大写的优惠券代码,这是没有意义的。”

From the way you describe your situation, it actually does seem to make sense to store these coupon codes in consistent case (either upper or lower) to match the consistent case (either strtoupper 'd or strtolower 'd) of the customer input. 从描述情况的方式来看,将这些优惠券代码以一致的大小写(大写或小写)匹配客户输入的一致大小写( strtoupperstrtolower )似乎确实有意义。

That said, regexp case-insensitive matching is achieved using the /i modifier. 也就是说,使用/i修饰符可实现不区分大小写的regexp匹配。

But strcasecmp() , which has already been suggested, is most likely a better solution. 但是已经建议的strcasecmp()最有可能是更好的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM