Drongo_III Posted January 25, 2015 Share Posted January 25, 2015 Hello So I want to try and match everything preceding a file extension in a string using preg_match. An example file name: "Images_home_blah.blah.jpg" . I've tried the following regex: /^([a-z0-9_\-\.]+)(?!\.jpg)/i But this sadly appears to capture the whole string instead of ignoring the '.jpg' part. Can anyone point me in the right direction? Thanks, Drongo Quote Link to comment Share on other sites More sharing options...
Ch0cu3r Posted January 25, 2015 Share Posted January 25, 2015 Change the negative look ahead (?! ...) to a positive look ahead (?=...) Quote Link to comment Share on other sites More sharing options...
Drongo_III Posted January 25, 2015 Author Share Posted January 25, 2015 Thanks Ch0 That worked a treat. I've just re-read some tutorials on positive and negative lookaheads but something is confusing me. If I had a pattern like this: '/^([a-z0-9_\-\.]+)(?!\.jpg)$/i'; Why is it that preg_match matches the whole string (i.e. including the .jpg)? Doesn't that pattern mean "match alphabetical, numeric, underscore, dash and full stop BUT don't match if the string ends in .jpg"? So by my understanding, which appears to be wrong, that shouldn't have matched anything. Thanks, Drongo Quote Link to comment Share on other sites More sharing options...
Zane Posted January 26, 2015 Share Posted January 26, 2015 Why do you want to use regex when you could just as easily use PHP's plethora of string functions $filename = "some_thing_that.has.dots.in.the_filename.jpeg"; $last_period = strrpos($filename, '.'); if($last_period !== false) $extension = substr($filename, $last_period+1); else echo "No extension found"; And.. there is also a specific function that will grab the extension in one line of code. $extension = pathinfo($filename)['extension']; Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.