开发者

PHP: Need to extract certain part of string using preg_match()

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?


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


Change .? by [^_]

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜