Jump to content

How to match CSS comments?


Wuhtzu

Recommended Posts

Hey

 

I'm trying to match and grab css comments from .css files, but I'm having troubles getting it 100% right.

 

The comments look like:

 

/* This is a css comment */

/* This is a multiline css comment
============================*/

/* Troublesome * / css comment containing characters from the closing tag */

 

 

This will match all the comments but the ones containing a * anywhere other than in the opening and closing tag. I could do the same with with the / (slash) but it would do the same thing. This is a problem since css comments can contain both * (stars) and / (slashes).

 

Notice @ is the delimiter (ran out of better ideas)

'@(/\*[^*]*\*/))@s'

 

 

Another thing which obviously does not work is:

'@(/\*.*\*/))@s'

 

Since it will match anything between the first opening tag and the last closing tag in the document, including other comments. So this will basically return the whole style sheet.

 

Can you guys think of a way to match those comments?

 

 

It seems doable: http://www.lonniebest.com/FormatCSS/

 

 

Best regards

Wuhtzu

 

 

 

Link to comment
https://forums.phpfreaks.com/topic/92096-how-to-match-css-comments/
Share on other sites

This worked fine for me:

 

<?php
  $css = "/* This is a css comment */

/* This is a multiline css comment
============================*/

/* Troublesome * / css comment containing characters from the closing tag */";

if(!preg_match_all('/\/\*(.+?)\*\//s',$css,$matches))
  die("Could not match");
print_r($matches[1]);
?>

 

output:

Array
(
    [0] =>  This is a css comment 
    [1] =>  This is a multiline css comment
============================
    [2] =>  Troublesome * / css comment containing characters from the closing tag 
)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.