Got more questions? Find advice on: ASP | SQL | XML | Windows
in Search
Welcome to RegexAdvice Sign in | Join | Help

Changing relative image paths

Last post 07-08-2008, 10:39 AM by ddrudik. 2 replies.
Sort Posts: Previous Next
  •  07-08-2008, 7:17 AM 43861

    Changing relative image paths

    Hi,

    My knowledge of regular expressions is practically nothing and I'm tearing my hair out trying to correct some buggy code in PHP.

    What it needs to do is change the path (by adding "newdirectory/" to the start of the path) for all images in the HTML that are relatively linked i.e. the path to the image does not begin with "http://", "https://" OR "/", where an image path is identified as being a string between single or double qoutes ending in .gif, .jpg, .jpeg or .png - this includes all images referenced in inline style backgrounds and as values in option tags for dropdowns.

    Examples where then path should be matched and adjusted:

    <img src="../image/my.gif" height="10px">  ->  <img src="newdirectory/../image/my.gif" height="10px">

    <div style='background-image: URL('image/my.png')' />  ->  <div style='background-image: URL('newdirectory/image/my.png')' />

    <option value="my.jpg">  ->  <option value="newdirectory/my.jpg">

    Examples where then path should NOT be matched:

    <img src="http://mydomain/image/my.gif" height="10px">

    <div style='background-image: URL('/image/my.png')' />

    <option value="http://antoherdomain/my.jpg">

    What I'm working with at the moment is /(?i)([^=\"\'\s]*?(\.(jp?g|gif|png)))/ but it doesn't exclude images with absolute paths.

    Please advise.

  •  07-08-2008, 9:24 AM 43870 in reply to 43861

    Re: Changing relative image paths

    Okay, I think I'm making progress. This is what I've got to now (although I don't understand it):

    (?<=["'])(?!http://|/)(.*?)?(\.(jp?g|gif|png))(?=["'])

    Am I on the right track?

  •  07-08-2008, 10:39 AM 43885 in reply to 43861

    Re: Changing relative image paths

    This example that should not be matched is a relative URL, was that typo in your example?

    <div style='background-image: URL('/image/my.png')' />

    This seemed to work with your limited sample:

    (?is)(?<=(["']))(?:(?!http://|\1).)*?(?:\.(?:jpe?g|gif|png))(?=\1)


View as RSS news feed in XML