user8950690
user8950690

Reputation:

preg_match to find specific string followed by arbitrary numbers

I have the HTML markup of a web page as $subject. I'm using preg_match to search for a particular string artist_x? and trying to return just the x portion. x can be any number ranging from 1 to 12 digits. So, the pattern would have to match any/all of the following:

artist_1?
artist_12345?
artist_123456789012?

...and bring back:

1
12345
123456789012

...respectively.

This is the closest I can come up with:

$pattern = '|[artist_][0-9]{1,12}|';
preg_match($pattern, $subject, $matches);

But it's not working right... It's finding the string I'm looking for and even returning the expected number, but the returned number still has the underscore prepended. I've tried quite a few solutions to get this far, but am out of ideas.

Thanks!

Upvotes: 2

Views: 1309

Answers (1)

Axnyff
Axnyff

Reputation: 9954

I don't really understand what your pattern is supposed to do. Anyway, this should work: you just capture the number that interest you. $matches will be an array containing first the whole match and then the group. So the first group will be what you want.

$subject = "artist_3333";
$pattern = '/artist_(\d{1,12})/';
preg_match($pattern, $subject, $matches);
echo($matches[1]); // 3333

\d in here means the same thing as [0-9], it matches digits

Upvotes: 2

Related Questions