Ydhem
Ydhem

Reputation: 928

Preg_match doesn't work while trying to get numbers in a string

Hum.. I mean I can't make it work... So here is what I did..

$url = 'http://test/test/9244349';
$test = preg_match('#\d*#', $url, $matches);

array (size=1) 0 => string '' (length=0)

I just want to catch "9244349" but I don't figure out why it's not working.

Upvotes: 1

Views: 593

Answers (4)

Tim Pietzcker
Tim Pietzcker

Reputation: 336158

Let's play regex engine:

  • \d* means any number of digits. Including zero.
  • We start at the beginning of the string. We see an h.
  • h doesn't match \d.
  • But - we're also allowed to match zero repetitions of \d. So the empty string before h matches.
  • We've reached the end of the regex, and we've found a match.
  • Achievement unlocked!
  • (of course, it's a match of zero characters, but that's OK. A Perl-compatible regex will always return the leftmost possible match, even if there may be further matches up ahead in the string that could be longer).

So, as mentioned in other posts, change the * to + to force at least one digit to match, then the rest will follow.

You could also use preg_match_all(), but then you'd get a lot of empty matches, one for each position between two non-digits...

Upvotes: 1

Shakti Singh
Shakti Singh

Reputation: 86386

This is basename

echo basename($url);

Upvotes: 0

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76395

Try replacing * with +, if you want to match digits, there's no point in a pattern that matches, zero digits, too, is there?

preg_match('/\d+/','http://test/test/9244349',$matches);
echo $matches[0];//output:9244349

Upvotes: 1

Denis Ermolin
Denis Ermolin

Reputation: 5546

Change * to + and it will work

Upvotes: 0

Related Questions