jack
jack

Reputation: 525

matching 9 digit string

I am trying to match a 9 digit numeric string with the following code but it only returns this < Looking at the source code of the remote page here is an example of what I am trying to match &cd=225730313"

$url = file_get_contents($source);
preg_match('/([0-9]{9})/', $match);
echo $match[0];

Upvotes: 0

Views: 1575

Answers (3)

KingCrunch
KingCrunch

Reputation: 131891

$url = file_get_contents($source);
preg_match('/([0-9]{9})/', $match);
echo $match[1];

Index 0 contains the match against the whole pattern, 1 the first subpattern and so on.

Edit:

To get the digits after &cd= I would suggest to expand the pattern, that it matches this too.

/&cd=([0-9]{9})/

Upvotes: 0

Emil Vikstr&#246;m
Emil Vikstr&#246;m

Reputation: 91942

You forgot the second parameter to preg_match. You ay also consider fetching the parenthesis (index 1) instead of the whole pattern (index 0).

$url = file_get_contents($source);
preg_match('/([0-9]{9})/', $url, $match);
echo $match[1];

I think the reason you get < is because you have used $match previously and it contains a string beginning with <. preg_match as used in your question will not change $match, and therefore $match[0] is the first character of the string contained in $match (strings can be accessed like arrays in PHP).

Upvotes: 4

Spyros
Spyros

Reputation: 48626

How about :

preg_match('/^[0-9]{9}+$/', $match) 

or maybe this :

preg_match('/\d{9}/', $match)

Upvotes: 0

Related Questions