Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

php - Regular expression to remove CSS comments

I want to write the regular expression in php for matching the line within a double and single quotes. Actually I am writing the code for removing comment lines in css file.

Like:

"/* I don't want to remove this line */"

but

/* I want to remove this line */

Eg:

- valid code /* comment */ next valid code "/* not a comment */" /* this is comment */

Expected result:

- valid code next valid code "/* not a comment */"

Please any one give me a regular expression in php for my requirement.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The following should do it:

preg_replace( '/s*(?!<")/*[^*]+*/(?!")s*/' , '' , $theString );

Test case:

$theString = '- valid code /* comment */ next valid code "/* not a comment */" /* this is comment */';

preg_replace( '/(?!<")/*[^*]+*/(?!")/' , ' ' , $theString );

# Returns 'valid code next valid code "/* not a comment */" '

Revision : 28 Nov 2014

As per comments from @hexalys, who referred to http://www.catswhocode.com/blog/3-ways-to-compress-css-files-using-php

The updated regular expression, as per that article, is:

preg_replace( '!/*[^*]**+([^/][^*]**+)*/!' , '' , $theString );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...