【问题标题】:Preg_match with different combinations of wordsPreg_match 与不同的单词组合
【发布时间】:2026-01-17 20:45:02
【问题描述】:

我有一个关于 preg_matches 的小问题,这些正则表达式的东西真的很难理解,我希望有人能给出正确的 awnser!

我有以下文字:

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()函数。

【问题讨论】:

  • 感谢您的标记(抱歉)。我没有真正尝试过任何事情,因为我对正则表达式一无所知......我读了一些文章,但我真的不清楚......
  • @user1939649 和我一样 :) 但是你能详细解释一下你的问题是什么类型的过滤吗?
  • 就像我说的,我有一个 php 脚本,可以从 javascript 帖子中获取以下格式的信息 0A-24-423 但这也可以是:0A-242-2 或 0A-2 -423 首先,我只有 1 种格式:A-2-2,我只是为此添加了 substr,但现在我有了这些不同类型的输入格式(动态生成!)我必须使用 preg_matches(至少这是我能找到的替换 substr)
  • 一分钟你能解释一下什么是0A和242和423吗?我可以帮你!
  • @Aspiring Aqib 我已经更新了第一篇文章

标签: php preg-match substr


【解决方案1】:

看起来您不需要使用正则表达式。这是一个使用explode()list() 的示例:

list($row_id, $order, $column_id) = explode('-', $seat, 3);

然后您可以在 $selectQuery 中使用这三个新变量。

【讨论】:

  • 老兄,你摇滚!完全忘记了 explode() 函数,谢谢一百万!
【解决方案2】:

编辑:由于 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 如果匹配。

【讨论】:

  • 感谢您的模式,我不是说英语的人,所以解释起来有点困难;)它是动态的,您可以按如下方式对输入进行交互:XX-XXX-XXX where XX will be replace通过数字或字符(ABCDEFG 等)我用正确的解释更新了第一篇文章
  • @user1939649 根据评论更新了我的答案。