简体   繁体   English

使用php检查字符串是否包含10位数字,但每个数字后面有空格

[英]Check if string contains 10 digit number but space after each digit using php

Suppose 假设

$str = "hi hello 1 2 3 4 5 6 7 8 9 0 ok"

so the match found. 所以比赛找到了。 I have tried with regex like 我试过像正则表达式一样

preg_match_all('/[0-9 ]{20}/', $str, $matches, PREG_OFFSET_CAPTURE);
print_r($matches);

but it matches others also 但它也与其他人相匹配

Try using the following pattern: 尝试使用以下模式:

\b[0-9](?: [0-9]){9}\b

Your updated code: 您更新的代码:

$str = "hi hello 1 2 3 4 5 6 7 8 9 0 ok";
preg_match_all('/\b[0-9](?: [0-9]){9}\b/', $str, $matches, PREG_OFFSET_CAPTURE);
print_r($matches[0][0]);

Array ( [0] => 1 2 3 4 5 6 7 8 9 0 [1] => 9 )

The reason for placing the word boundaries ( \\b ) around both sides of the pattern is to prevent a false match along the lines of the following 将边界( \\b )放置在图案两侧的原因是为了防止沿着下面的线条进行错误匹配

10 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 012

That is, we need to make sure that the first and final digits are in fact single digits by themselves, and not parts of larger numbers. 也就是说,我们需要确保第一个和最后一个数字本身实际上是单个数字,而不是更大数字的部分。

Try this ! 尝试这个 !

Regex : 正则表达式:

(?:[0-9][ ]){10}

Verify through regex101 : 通过regex101验证:

在此输入图像描述

your regex is matching space before the first number, that is the problem 你的正则表达式是在第一个数字之前匹配空格,这就是问题所在

[0-9 ]{20}

To correct it by starting with [0-9] you enforce the first match to be a number and adjust a space followed by a number( [ ][0-9] ) 9 times. 要通过以[0-9]开头来纠正它,请将第一个匹配强制为数字并调整空格,然后调整数字( [ ][0-9] )9次。

[0-9](?:[ ][0-9]){9}

demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM