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
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 
)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.