我需要有关正则表达式(PHP)的帮助。因此,我有一个文本框,用户可以在其中输入订单。
例如:
see north,
see south,
sell 7 wood,
see west
我需要一个符合以下规则的正则表达式:
到目前为止,我已经做了以下正则表达式:
preg_match("/(((see) (north|south|west|east))|((sell|buy) ([1-9][0-9]{0,2}) (wood)))/");
但问题是,以下输入也有效,不应为:卖出75木材见北(应该卖出75木材或见北)
注意!现在,我的正则表达式中没有逗号验证,因为我使用PHP函数爆炸以逗号分隔,然后将结果数组项传递给正则表达式。但它似乎不适用于以下输入:
see north,
see south *(no comma between two orders)*
sell 7 wood,
see west
因此,我需要以下解决方案之一:
谢谢。
请勿为此使用正则表达式。这是(基本)解析器的工作。
做任何您需要一次获得一个命令的事情。explode
例如,这可能是。trim
如有必要,请使用其从开头和结尾删除空格。
然后, $parts = explode(" ",$command);
现在switch($parts[0])
,您可以根据第一个关键字来确定要做什么。
case "see":
if( !in_array($parts[1], ["north","south","east","west"])) {
throw new OutOfBoundsException("Invalid direction");
}
// do something here
break;
请注意,验证非常容易,并且可以提供特定的错误消息,以便用户知道他们做错了什么。
case "sell":
$q = intval($parts[1]);
if( $q < 1 || $q > 999) {
throw new OutOfBoundsException("Invalid amount of things to sell");
}
$what = $parts[2];
if( !in_array($what, ["wood"])) {
throw new OutOfBoundsException("Invalid thing to sell");
}
// do something
break;
default:
throw new OutOfBoundsException("Invalid command");
这整个过程都是要解决一个大问题并将其分解。更改其工作方式,允许使用哪些命令和参数等也非常非常容易。更改正则表达式会更加困难。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句