知道如何修改正则表达式以检查邮政编码或地址


Any idea how to modify regex to check for zipcode or address?

下面的代码遵循正则表达式中定义的规则。

  1. 如果 ID 都是数字,则在前 2 位数字后插入一个空格。
  2. 如果 ID 在前 2 位数字之后有一个字符,并且没有其他字符,则不会更改。
  3. 如果 ID 包含数字和字符,并且字符在数字中的任何位置是 GG,则在 GG 之前插入 2 个空格。

我在下面的代码满足这些规则。

这些规则旨在改进生产模式下的当前搜索功能。

我们在实施这些规则后遇到的问题是双重的。

1,用户可以使用当前生产应用程序使用ID,邮政编码和地址进行搜索,并在搜索参数有效时获得结果。

实施这些规则后,邮政编码搜索和地址搜索不再起作用。

例如,与 ID 一样,如果用户使用 ID 进行搜索,则输出的结果仅是用户搜索时使用的 ID。然后,用户单击该 ID。

与邮政编码相同,在大多数情况下,地址的工作方式取决于用户是输入完整地址还是地址的一部分,在这种情况下,将显示与输入部分匹配的地址。

邮政编码和地址在我们的开发服务器中不适用于这个新的修改版本。

我将永远感激任何帮助弄清楚为什么代码在模式后停止工作。

我想出了正则表达式,但其他人写了查询。

function format($matches)
{
    return $matches[1][0].(strlen($matches[2][0])>0?$matches[2][0]:" ").$matches[3][0].(strlen($matches[4][0])>0?"  ".$matches[4][0]:"");
}
// construct regular expression
$pattern
= '/'         // regex delimiter
. '('         // START of a capture group
. ''d{2}'     // exactly two digits
. ')'         // END of capture group
. '('         // START SECOND capture group
. '['sND]?'     // letters "D" OR "N" in any order or number - This is optional
. ')'         // END SECOND capture group
. '('         // START THIRD capture group
. ''d*'       // any number of digits
. ')'         // END THIRD capture group
. '('         // START FOURTH capture group
. 'GG'        // the letters "GG" EXACTLY
. '['d]*'     // any number of digits
. ')'         // END THIRD capture group
. '?'         // make the LAST capture group OPTIONAL
. '/'         // regex delimiter
;
// get current matche
preg_match_all($pattern, $_GET['id'], $matches);
// reformat the match
$str = format($matches);

// query
$tsql = "SELECT *
FROM searchtable AS ST
inner join CONTAINSTABLE(gSearch, Name, ''"$id*'"') AS GT
ON ST.GUID = GT.[KEY]
WHERE GT.RANK > 0
ORDER BY list, Name, GT.RANK DESC";

如果有帮助,这些是我在编写正则表达式后所做的更改。

我更改了当前在生产中工作的内容:

$id= $_GET["id"];

对此:

// get current matche
preg_match_all($pattern, $_GET['id'], $matches);
// reformat the match
$str = format($matches);

我没有弄乱查询,所以我认为我的问题与正则表达式有关。

提前非常感谢

似乎分

步完成会更容易、更智能、更易于维护:

$search = $_GET['id'];
if (preg_match('/^'d+$/', $search)) { // Only digits
    $search = substr($search, 0, 2).' '.substr($search, 2);
} else if (preg_match('/^'d+?GG'd+?$/', $search)) { // 'GG' between digits
    $search = str_replace('GG', '  GG', $search);
}
// query
$tsql = "SELECT *
FROM searchtable AS ST
inner join CONTAINSTABLE(gSearch, Name, ''"$search*'"') AS GT
ON ST.GUID = GT.[KEY]
WHERE GT.RANK > 0
ORDER BY list, Name, GT.RANK DESC";