Jump to content

Not matching extensions - preg_match


Drongo_III

Recommended Posts

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

Link to comment
https://forums.phpfreaks.com/topic/294224-not-matching-extensions-preg_match/
Share on other sites

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

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'];

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.