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
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

Link to comment
Share on other sites

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'];
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.