tags:

views:

46

answers:

3

I'm try to extract the "INV" part of the string below:

123_456_P1234_INV_UID-123456.PDF

Here's the code I have so far:

php -r 'echo preg_match("/_(.*?)_UID-.*?\.PDF$/", "123_456_P1234_INV_UID-123456.PDF", $cat) ? $cat[1]."\n" : "";'

This returns:

_456_P1234_INV

Can anyone tell me why it's including everything before the INV bit? How can I fetch just the INV part please?

+3  A: 

Because the .* swallows everything, including _. Try this:

php -r 'echo preg_match("/([^_]*?)_UID-.*?\.PDF$/", "123_456_P1234_INV_UID-123456.PDF", $cat) ? $cat[1]."\n" : "";'

Update, after reading the answer to the comment on another answer:

php -r 'echo preg_match("/([^_]*_UID-.*)\.PDF$/", "123_456_P1234_INV_UID-123456.PDF", $cat) ? $cat[1]."\n" : "";'
Johan
Perfect, thanks! :)
Reado
What's the difference between the two?
Reado
The position of the ending parenthesis. It depends on if you want to have everything after INV or not.
Johan
+1  A: 

Change .*? by [^_]*

php -r 'echo preg_match("/_([^_]*)_UID-.*?\.PDF$/", "123_456_P1234_INV_UID-123456.PDF", $cat) ? $cat[1]."\n" : "";'
M42
That works, thanks!
Reado
A: 

From the () use you just want whatever is in INV correct? If you're sure there is always a UID after this should work, NOTE: that INV can NEVER contain _.

php -r 'echo preg_match("/_(.[^_]*?)_UID-.*?\.PDF$/", "123_456_P1234_INV_UID-123456.PDF", $cat) ? $cat[1]."\n" : "";'
Viper_Sb