0

I consider myself fairly bright, but anything but the simples regex goes swoosh over my head I'm afraid.

I'm trying to figure out a preg_replace to replace all image links and add a timestamp (the usual fool-the-cache trick). So what I am looking for is a regex that would take

blah blah blah <a href='blah>blah</a> blah <img src="http://blah.com/test.jpg" /> blah blah <a href="blah"><img src='/tester.jpg' /></a> blah blah

and make it into

blah blah blah <a href='blah>blah</a> blah <img src="http://blah.com/test.jpg?timestamp=123" /> blah blah <a href="blah"><img src='/tester.jpg?timestamp=123' /></a> blah blah.

Is it possible to do it in a single preg_replace? If not, any suggestions on the best way to do this?

j08691
  • 204,283
  • 31
  • 260
  • 272
charliez
  • 163
  • 2
  • 14
  • [Do not parse HTML with regexes](http://stackoverflow.com/a/1732454/344643). Use an [XML parser](http://us2.php.net/manual/en/class.domdocument.php) instead. – Waleed Khan Feb 09 '13 at 22:13
  • Yes, it's possible with the right regular expression (unless the HTML is badly deformed). However, SO isn't about people writing code for you, so why not give it a go and then post your code if you need help? – Anton Feb 09 '13 at 22:14
  • Thank you, much appreciated after having helped people here myself. I'm saying I'm completely blank on this area, so I would have appreciated some pointers. – charliez Feb 09 '13 at 22:17
  • The problem is, and again I am frankly shit at regex, that I end up catching the whole text - so with ( the first $1 will contain the whole from first img tag up until the last img tag. – charliez Feb 09 '13 at 22:39

2 Answers2

1

HTML parsing is not so simple. But you can try something like this:

$search = "/(\<img[^>]+src=)(['\"])([^'\"]+)['\"]/i";
$result = preg_replace($search, '\1\2\3?timestamp='.$ts.'\2', $input);
fejese
  • 4,601
  • 4
  • 29
  • 36
1

You can run your page through a JQuery function:

var timestamp = '?timestamp=123';
$('img').each(function () {
  if ($(this).attr('src')) {
    $(this).attr('src', ($(this).attr('src') + timestamp));
  }
});

Here is an example.

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • Sorry, maybe my question was unclear. I had to do this serverside in PHP. The original question title made this clear, but a moderator changed it for one reason or another. Appreciate your input! – charliez Feb 10 '13 at 18:03