3

I hope you can help me create a regex that will extract the image name from a url. I've been trying to create the regex for a couple of days now but i cant get it to work.

The case: I have an image url created with phpThumb that looks like this: \bla\thumb\phpThumb.php?src=/bla/images/thisistheimage.jpg&fltr[]=wmt|40|B|FFFFFF|georgia.ttf|35&hash=b7412f04f09cd6b488435231651d61453

No i need the following extracted: thisistheimage.jpg

Some facts:

  • there is always a "/" in front of the image name;
  • the image name is always followed by an amp (&);
  • the image extention can also be: jpeg, JPG, png, PNG, gif;

All i have managed to grab was the image extension with (?:png|jpg|gif).

Can you please help me what regex I have to use in this case?

I'm able to use the regex in javascript or in PHP, where do you recommend it? (I use javascript to submit the form and the form action is done in PHP).

2
  • 1
    Re: "I'm able to use the regex in javascript or in PHP, where do you recommend it?": Remember that you cannot trust anything submitted in a form, because it comes from code that's outside your control. You may have written JavaScript code that interacts with your PHP page, but you cannot guarantee that that's the code being used to submit the form. So, absent a reason to the contrary, you should nearly always prefer to do something server-side, in PHP. Commented Oct 9, 2012 at 18:05
  • Further to ruakh's comment: JavaScript should be used for user-convenience, not for any form of data-security or sanitation. Always check server-side before storing anything submitted by, or from, the user. Commented Oct 9, 2012 at 18:08

2 Answers 2

4
/\/([A-Z0-9_-]{1,}\.(?:png|jpg|gif|jpeg))/i

I think that should work. i flag for insensitive case

  • matches slash /
  • Alphanumeric, , and - one or more [A-Z0-9-]{1,}
  • period .
  • extension (?:png|jpg|gif|jpeg)
Sign up to request clarification or add additional context in comments.

2 Comments

An improvement to match but ignore the leading slash: /(?!\/)([A-Z0-9_-]{1,}\.(?:png|jpg|gif|jpeg))/i
Works like a charm, thanks so much! your explanation helps me understand how and why it all works now. @Intelekshual : also thanks to you for thinking with us and post an inprovement!
0

since you have tagged , why dont you go through document.images and get the image you want?

like this:

// add a proxy to all images in the page

var proxy = 'https://proxytea.appspot.com/'

for (var x=0; x<document.images.length; x++) {
    imagem = document.images[x];
    imagem.src = imagem.src.replace(location.protocol + '//', proxy);
}

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.