I'm using this function to remove HTML comments from my code to save loading time:

// Remove unwanted HTML comments
function remove_html_comments($content = '') {
return preg_replace('/<!--(.|\s)*?-->/', '', $content);

But I also use wt3 cache plugin witch uses this to parse code inside his comment pattern:

$buffer = preg_replace_callback('~<!--\s*mfunc\s*' . W3TC_DYNAMIC_SECURITY . '(.*)-->(.*)<!--\s*/mfunc\s*' . W3TC_DYNAMIC_SECURITY . '\s*-->~Uis', array(
        ), $buffer);

I need to implement fragment caching to exclude some parts of my code from being cached, but that is not possible with the function that I use to strip code commenting because it will exclude all comments...

Is it possible to exclude all comments inside W3TC comment tags from being removed by the function that i'm using?

This is how I'm implementing on my theme:

In wp-config.php I've added

define( 'W3TC_DYNAMIC_SECURITY', md5( rand( 0, 999999 ) ) ); // random "secret"

In my template:

<!--mfunc <?php echo W3TC_DYNAMIC_SECURITY; ?> -->
<?php echo  rand(0,1000); ?>
<!--/mfunc <?php echo W3TC_DYNAMIC_SECURITY; ?> -->

Try slapping a negative lookahead before the comment match, eg

function remove_html_comments($content = '') {
    return preg_replace('/(?!<!--\s*\/?mfunc\s*' . W3TC_DYNAMIC_SECURITY . ')<!--(.|\s)*?-->/', '', $content);
  • I think this could work... Right now, it only excludes from remotion the first part of the comment but doesn't closes it. This is how is outputting: <!--mfunc db26fe44e57fcb1474e4094247b0252e --> 148<div class="clear" style="margin-top:30px;"></div> and I think it should be like this: <!--mfunc db26fe44e57fcb1474e4094247b0252e --> 148 <!--/mfunc db26fe44e57fcb1474e4094247b0252e --> – Alex Nov 4 '15 at 13:39
  • Ah I missed the closing slash - will update answer – bonger Nov 4 '15 at 13:47
  • now it stop working... :-( – Alex Nov 4 '15 at 14:01
  • Hmm just tried it on '<!--blah--> asdfasdf <!--mfunc db26fe44e57fcb1474e4094247b0252e --> 148 <!--/mfunc db26fe44e57fcb1474e4094247b0252e --><div class="clear" style="margin-top:30px;"></div><!-- blah wow gosh--> hemm' and it worked (returning asdfasdf <!--mfunc db26fe44e57fcb1474e4094247b0252e --> 148 <!--/mfunc db26fe44e57fcb1474e4094247b0252e --><div class="clear" style="margin-top:30px;"></div> hemm)... – bonger Nov 4 '15 at 14:09
  • Maybe this is a problem on my side... I don't have a clue why, but the truth is that it stopped working... I don't know if I have this well explained but the RegExp should exclud all regular HTML comments and left intact all the ones that start with <!--mfunc mysecuritystring --> and end with <!--/mfunc mysecuritystring --> – Alex Nov 4 '15 at 14:28

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.