0

wget does a good job of pulling down prerequisite files, but it cannot detect image paths inside a JS file. I need a regex to scan JS files for any image paths it finds.

These paths would generally be nested as follows:

$img1 = "foo/bar.png";
$img2 = 'foo/bar.jpg';
$img3 = "{'myimg':'foo/bar.png'}";

I need a regex which will be able to pick up the whole image path inside the quotes, but sometimes nested inside a json string, or otherwise encoded... essentially, matching a whole image path by detecting just the existence of the extension (jpg|png|gif).

4
  • What about $path = "/foo"; $img = $path + "bar.png";? Commented Jun 14, 2013 at 15:18
  • The regex needs to be able to detect the existence of any image. The path is unknown, and the filename is unknown - for example we could have /wp-content/uploads/myimage.png or /images/bigredbus.jpg. I need to be able to isolate the image paths so that I can download them. I don't need to construct an image path, rather detect and return an image path within the JS file. Commented Jun 14, 2013 at 15:22
  • I know; I'm asking, what about paths which are built programmatically, that a regular expression can't possibly find? Commented Jun 14, 2013 at 15:23
  • Ah, sorry! The regex just needs to be a "best fit". I appreciate that some instances cannot be catered for (or moreso can, but will be factored in at a later stage). For now if I can find full paths, I'll work on a path constructor at a later stage :) Commented Jun 14, 2013 at 15:27

1 Answer 1

1

Try with this pattern:

$pattern = '~/?(?>[^"\'/]+/)+[^"\'\s]+?\.(?>png|jpe?g|gif)\b~';
Sign up to request clarification or add additional context in comments.

2 Comments

This is the best fit so far - thanks! It needs to account for spaces in urls too, such as "/path/to img/foo.jpg". Can you please edit the regex to include support for this? Thanks.
How to format this regex so that it can work in javascript?

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.