tags:

views:

58

answers:

2

Hello there,

Given the following string how can I match the entire number at the end of it?

$string = "Conacu P PPL Europe/Bucharest 680979";

I have to tell that the lenght of the string is not constant.

My language of choice is PHP.

Thanks.

+7  A: 

Hi,

You could use a regex with preg_match, like this :

$string = "Conacu P PPL Europe/Bucharest 680979";

$matches = array();
if (preg_match('#(\d+)$#', $string, $matches)) {
    var_dump($matches[1]);
}

And you'll get :

string '680979' (length=6)

And here are some informations :

  • The # at the begining and the end of the regex are the delimiters -- they don't mean anything : they just indicate the begining and end of the regex ; and you could use whatever character you want (people ofen use / )
  • The '$' at the end of the pattern means "end of the string"
  • the () means you want to capture what is between them
    • with preg_match, the array given as third parameter will contain those captured data
    • the first item in that array will be the whole matched string
    • and the next ones will contain each data matched in a set of ()
  • the \d means "a number"
  • and the + means one or more time

So :

  • match one or more number
  • at the end of the string

For more informations, you can take a look at PCRE Patterns and Pattern Syntax.

Pascal MARTIN
Is there any particular advantage to using # around your regex instead of /? Just for my own curiosity?
Mark Biek
Thank you, it works just fine.
Psyche
You don’t need the grouping. `$matches[0]` already contains the whole match.
Gumbo
Not in this case, but in some cases it makes sense, when you want to use /'s in your regex as a character to match. Some people just do this sort of thing out of habit (I usually use an @ sign for instance)
Matthew Scharley
@Mark : not in this case ; but there would be a difference if the pattern did contain some slashes (like a portion of an URL, for instance) ;; @Psyche : you're welcome ;; @Gumbo : true ; but I prefer having the grouping already in place since the beginning, for the day I'll have to modify the pattern to add more stuff : this way, I won"t have to modify the rest of the code
Pascal MARTIN
+1  A: 

The following regex should do the trick:

/(\d+)$/
Jani Hartikainen