Jump to content

regex - extract last group of numbers in a string


markjohnson

Recommended Posts

One way could be:

 

$string="this-is-my-uri--8271";
preg_match('#[0-9]+$#', $string, $match);
echo $match[0]; // Output: 8271

 

If it will always be certain to have 4 digits at the end, another possible solution could involve the use  of substr:

 

$numbers = substr($string, -4, 4);

 

Depending on the circumstances, regex may not be needed.

ugh. beat me to it. 

 

you know nrg, i don't know if it's a good sign or a bad sign that our regex solutions usually always come out almost exactly the same.  Well this is a simple example. Kind of hard to not come out the same.  But i've noticed on more complex examples the same thing.  Except you're partial to # I'm partial to ~

 

Thanks! It did the trick.

 

One way could be:

 

$string="this-is-my-uri--8271";
preg_match('#[0-9]+$#', $string, $match);
echo $match[0]; // Output: 8271

 

If it will always be certain to have 4 digits at the end, another possible solution could involve the use  of substr:

 

$numbers = substr($string, -4, 4);

 

Depending on the circumstances, regex may not be needed.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.