0

I wanted to use regular expression to check if a string has a word that contains 8 digit of alphanumeric character, ignoring uppercase and lowercase (meaning that 2HJS1289 and 2hjs1289 should match). I know I can use preg to do this, and so far I have this:

preg_match('/[A-Za-z0-9]/i', $string)

I am unsure however on how to limit it only to 8 digits/character scheme.

4

3 回答 3

2

对于恰好 8 个字符的单词,您需要使用单词边界:\b

preg_match('/\b[A-Z\d]{8}\b/i', $string)
于 2013-09-13T01:55:27.487 回答
1

尝试

preg_match('/\b([A-Z0-9]{8})\b/i', $string)

{8} 精确匹配 8 次。我添加了捕获组(括号),以防您需要提取实际匹配。

您还可以使用 {min,max} 来匹配在 min 和 max 时间之间重复的模式(我认为包括在内)。或者,您可以保留其中一个参数以使其保持开放状态。例如 {min,} 至少匹配 min 次

于 2013-09-13T01:09:30.990 回答
0

[a-zA-Z0-9] - 将匹配大小写字母或数字

{8} - 将指定匹配前一个令牌的 8 个

把它放在一起:

 preg_match('/([A-Za-z0-9]{8})/i', $string)

例子

于 2013-09-13T01:09:58.013 回答