我有一个关于preg_matches的小问题,这些正则表达式的东西真的很难理解,我希望有人能给正确的答案!
我有以下文本:
0A-24-423
但也可以是:
0A-242-2
或
0A-2-423
我如何使用preg_matches来过滤这些?我用的是
substr($something, 0,2)
以便它捕获0A和
substr($seat, 4,5)
这将捕获24,但当你得到242时,它不会捕获最后2....
希望有人可以帮助创建这个preg_match!
让它更清楚我现在有什么:
foreach($_POST['seats'] AS $seat) {
if ($count > 0) {
$selectQuery .= " || ";
}
$selectQuery .= " ( rowId = '" . substr($seat, 0,2) . "'";
$selectQuery .= " and `order` = " . substr($seat, 3,5) . " ";
$selectQuery .= " and columnId = " . substr($seat, 6) . " ) ";
$count++;
和$seat有以下格式XXXXXX,使用substr我可以得到正确的东西(例如:0J3017)
应该这样做:
$selectQuery = "SELECT * from seats where ";
$count = 0;
$pattern = "I DON'T KNOW :( ";
foreach($_POST['seats'] AS $seat) {
if ($count > 0) {
$selectQuery .= " || ";
}
preg_match($pattern, $seats, $matches);
$selectQuery .= " ( rowId = '" . $matches[0] . "'";
$selectQuery .= " and `order` = " . $matches[1] . " ";
$selectQuery .= " and columnId = " . $matches[2] . " ) ";
$count++;
和$seats在文章的开头有解释(它的格式是XX-XXX-XXX
where the first 2 XX are 0[A-Z] (yes the 0 is correct)
where the 3 first XXX are [0-9]
Where the last 3 XXX are [0-9]
编辑:有两种方法可以解决这个问题。
选项1:
$pattern = "/(.*)-(.*)-(.*)/";
看起来您不需要使用正则表达式。下面是使用explode()
和list()
的示例:
list($row_id, $order, $column_id) = explode('-', $seat, 3);
然后您可以在$selectQuery
中使用这三个新变量。
编辑:由于OP已经将他的要求作为对我的回答的评论,我已经相应地更新了我的回答。
你可以试试:
$pattern = "/[A-Z'd]{1,2}-[A-Z'd]{1,3}-[A-Z'd]{1,3}/";
$matched = preg_match($pattern, $something);
if ($matched === 0) {
die('regex did not match');
}
$matched
将为匹配的字符串提供1
,如果不匹配则提供0
。