$buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
And is there any place I can learn regular expressions? I know the basics.
$buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
And is there any place I can learn regular expressions? I know the basics.
This seems to be used to match the comments /* … */
:
/\*
matches the leading /*
[^*]*\*+
matches any following characters except *
followed by one or more *
([^/][^*]*\*+)*
matches zero or more sequences of characters beginning with any character except /
(to avoid a premature end since the last character is a *
), followed by any character except *
, followed by one or more *
/
matches the ending /
Precise the context where is used the regexp, it might be helpful.
It does what in says in the comment above that line. It removes comments (from CSS files).
You likely found it at
! # ... Beginning of the regex...
/ # 1. Match a slash
\* # 2. and an asterisk
[^*]* # 3. followed by some non-asterisks
\*+ # 4. and then at least 1 asterisks
( # And then some groups of
[^/] # 5. match a non-slash
[^*]* # 6. followed by some non-asterisks
\*+ # 7. and then at least 1 asterisks
)* #
/ # 8. And finally a slash
! # ... End of the regex ...
.——————<—————————————<————————————. .———<——. .——<——. | .——<———. .——<——. | | | | | | | | | | | [ / ]—>—[ * ]—>—o—[^*]—' .—>—[ * ]—>—o—>—o—>—[^/]—>—o—[^*]—' .—>—[ * ]—>—o—' .—>—[ / ] | | | | | | '————>———' | '———>————' | '——————>——————————————>—————————————' 1 2 3* 4+ ( 5 6* 7+ )* 8
Example instance:
/* blah *** f /* foo*** */
12333333444566675666777578
This is used to remove C-style comments.
It means somebody was drunk.
Seriously, I don't even want to try decoding that completely, but it looks like it was designed to replace some combination of forward slashes and asterisks with nothing (e.g. remove them).
That's the kind of regex that gives regexes a bad name.
In addition to Chris's suggestion of regular-expressions.info, you should actually review the reference docs for PHP's regexes, which are actually PCREs (Perl Compatible Regular Expressions), meaning you should probably also read through the Perl regex docs.
It's been ages since I picked up an edition of it, but I seem to recall that Mastering Regular Expressions from O'Reilly was a good book on regexes in general:
Taking things one step at a time:
The ! are just used as a delimiter for the start/end of the regex, so they aren't used for matching.
/\*
matches a forward slash followed by a star (the star is a special character so is escaped by a backslash).
[^*]*
matches 0 or more characters that aren't stars.
\*+
matches one or more stars.
[^/]
matches anything but a forward slash
[^*]*
matches 0 or more characters that aren't stars.
\*+
matches 1 or more stars.
The last bit in brackets, followed by a star, matches that section 0 or more times.
/
matches another forward slash.
Overall, that matches any pattern like /*asdf***asdfasdf***/
, ie it is matching that style of comment.