0

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?

1
  • Yes, though it may not always be "INV", which is why I'm using this method. Does that make sense? Commented Jul 30, 2010 at 14:51

3 Answers 3

3

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" : "";'
Sign up to request clarification or add additional context in comments.

2 Comments

What's the difference between the two?
The position of the ending parenthesis. It depends on if you want to have everything after INV or not.
0

Change .? by [^_]

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

Comments

0

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" : "";'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.