Bharat Godam
Bharat Godam

Reputation: 41

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

Upvotes: 3

Views: 703

Answers (3)

The Scientific Method
The Scientific Method

Reputation: 2436

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}

demo

Upvotes: 0

Usman
Usman

Reputation: 2029

Try this !

Regex :

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

Verify through regex101 :

enter image description here

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522064

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

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.

Upvotes: 1

Related Questions