0

How can I modify the following Regex to be NOT executed if the <img> tag is within <script> tags (respectively <script language="...">, meaning <script*>)

Code:

function seo_friendly_images($content) {

return preg_replace_callback('/<img[^>]+/', 'seo_friendly_images_process', $content);

}

add_filter('the_content', 'seo_friendly_images', 100);
Martin Ender
  • 43,427
  • 11
  • 90
  • 130
David Garcia
  • 3,056
  • 18
  • 55
  • 90
  • 1
    [Have you tried an HTML parser?](http://stackoverflow.com/a/1732454/476) – deceze Sep 25 '12 at 05:45
  • I was looking into it, is this conditional going the right way if (stripos($content, ' – David Garcia Sep 25 '12 at 05:47
  • [You shouldn't be using regex for that.](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454) However, [your problem is similar to this one.](http://stackoverflow.com/questions/12554005/c-sharp-regex-replace-in-string-only-outside-tags) – Martin Ender Sep 25 '12 at 05:48

2 Answers2

1

This depends a bit on the language you're using. Some languages support look ahead or look behind (e.g. match foo only when followed by bar or match bar only when preceeded by foo).

This looks like php to me which reports to have look ahead support (http://php.net/manual/en/regexp.reference.assertions.php).

Try using a regex like

    /<script[^>]+>(?=<img)/ or /<script[^>]+>(?!<img)/

?= indicates a positive look ahead and ?! indicates a negative look ahead. Positive look ahead meaning "Foo is followed by Bar", Negative look ahead meaning "Foo is not followed by Bar".

SnowInferno
  • 449
  • 3
  • 9
-1

You might want to try this:

return preg_replace_callback('<img[^<]+?>', 'seo_friendly_images_process', $content);

Not tested thouogh.

xmaestro
  • 1,084
  • 2
  • 16
  • 44