Preg_match具有不同的单词组合

时间:2012-12-31 12:43:19

标签: php preg-match substr

我有一个关于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++;

和$席位在帖子开头解释(格式为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()函数。

3 个答案:

答案 0 :(得分:1)

看起来你不需要使用正则表达式。以下是使用explode()list()的示例:

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

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

答案 1 :(得分:0)

编辑:由于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

答案 2 :(得分:0)

我知道这很复杂,但应该做你想做的工作。

$seats = '0a-11-2011';//example
$pattern = "/^([a-zA-Z0-9]*)-([a-zA-Z0-9]*)-([a-zA-Z0-9]*)$/";
preg_match_all($pattern, $seats, $matches);
unset($matches[0]);
foreach($matches as $match)
{
    $matches2[]=$match[0];
}
$selectQuery .= " ( rowId = '" . $matches2[0] . "'";
$selectQuery .= " and `order` = " . $matches2[1] . "  ";
$selectQuery .= " and columnId = " . $matches2[2] . " ) ";

Pattern是一种多模式,用于搜索具有3 -的字符串,并将每个部分作为数组元素返回。

但是你应该使用爆炸功能:

$matches = explode('-',$seats);
$selectQuery .= " ( rowId = '" . $matches[0] . "'";
$selectQuery .= " and `order` = " . $matches[1] . "  ";
$selectQuery .= " and columnId = " . $matches[2] . " ) ";

我在使用较少的代码和CPU能力时做同样的工作。