0

因此,我正在寻找一种使用 PHPpreg_match()函数验证字符串的方法。

第一个字符必须是字母,并且必须是J,RP。第二个字符必须是字母。字符 3-8 必须是数字。

任何人都对我如何做到这一点有一些指导?谢谢,麻烦您了。

4

4 回答 4

4

你在找/^[JRP][A-Z][0-9]{6}$/吗?

尸检:

  • ^- 字符串必须从这里开始
  • [JRP]- 字符“J”、“R”或“P”中的任一个
  • [A-Z]- 来自 AZ 的字母(大写)
  • [0-9][6}- 从 0 到 9 的数字精确匹配 6 次(所以你总共得到 8 个字符)
  • $- 字符串必须在这里结束

在 PHP 中使用:

if (preg_match('/^[JRP][A-Z][0-9]{6}$/', $string)) {
    echo "Matches!";
}

如果你想在文本中搜索,你可以跳过^并且$

if (preg_match_all('/[JRP][A-Z][0-9]{6}/', $string)) {
    echo "Matches!";
}

如果你希望它也匹配小写字母,你可以像这样添加a-z[A-Z]匹配中:[a-zA-Z].

于 2013-11-06T14:20:56.087 回答
1

这应该简单地完成工作

/^[JRP][A-Za-z]\d{6}$/
于 2013-11-06T14:20:59.980 回答
0
$string = 'JJ123456';

if (preg_match('/^J|R|P[a-zA-Z][0-9]{6}$/', $string))
{
    // Matched
}
else
{
    // Does not match
}
于 2013-11-06T14:21:26.970 回答
0
$val = "JA1234";
var_dump(preg_match("/^[JRP][a-zA-Z][0-9]{6}$/", $val));

在哪里:

^ - place of a start of string
$ - place of the end of string
so whole string should be matched with reqular expression
[JRP] - one of the letter from the list
[a-zA-Z] - one letter
[0-9]{6} - digit should be repeated 6 times
于 2013-11-06T14:27:50.083 回答