I'm looking for something, but don't exactly know what.

I have a shortcode, let's call it [shortcode].

Users will input HTML tags inside, mostly images, but also links, images in links, etc., for example:

<img src="http://www.site.com/myimage.jpg" />
<a href="http://www.blabla.com"><img src="http://www.site.com/myimage2.jpg" /></a>

The point is I want to format URLs, differently, I want every img src to start with files/myimagescript?

So the code above should output:

<!--- shortcode code before input -->
<img src="files/myimagescript?http://www.site.com/myimage.jpg" />
    <a href="http://www.blabla.com"><img src="files/myimagescript?http://www.site.com/myimage2.jpg" /></a>
<!-- shortcode code after input -->

So basically I need to simply change src of images. And it should work for any number of images, from 1 to unlimited.

I'm thinking about foreach PHP loop, but I'm not sure how to grab each img src line from shortcode and process it before displaying?


you can use regex to find your the src and use that to append your "files/myimagescript?" to it:

function append_myimagescript($attr, $content){ 
    $pattern = '/src="([^"]*)"/i';
    $replacement = 'files/myimagescript?${1}';
    return preg_replace($pattern, $replacement, $content);
  • 1
    Pretty much the only way to... there's no way you'd match the image src's inside the post without a regex...(which should have you thinking.... is the approach i want to take)... If ever you need regex... it's usually the wrong way to approach it... (impo of course)... – t31os Mar 9 '11 at 23:07
  • 1
    +1 to Bainternet though... i was thnking out loud more than anything... :) – t31os Mar 9 '11 at 23:07
  • @t31os if you say so! I'm changing my approach then, if using Regex is the wrong thing :) – Wordpressor Mar 10 '11 at 1:13
  • 1
    It's not the wrong way, i just think it's more ideal if you can find a way to tackle a problem without regex(they're not the fastest of operations). For this particular problem though regex is pretty much your only option. – t31os Mar 10 '11 at 11:26
  • I'd have to agree that if you find yourself depending on regex then that should be the last resort, how about a short code that takes the image src as an attribute as an alternative? – Bainternet Mar 10 '11 at 13:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.