Skip to content

Instantly share code, notes, and snippets.

@n18l
Last active February 21, 2020 22:29
Show Gist options
  • Save n18l/dcde0a456ad10c2ff49667005e758c12 to your computer and use it in GitHub Desktop.
Save n18l/dcde0a456ad10c2ff49667005e758c12 to your computer and use it in GitHub Desktop.
Regular expression to capture a selector within a stylesheet
<?php
/**
* Creates a regular expression string for properly capturing a specific CSS
* selector within a stylesheet. This regular expression ensures that the
* captured selector isn't actually a substring of another selector.
*
* As always, regular expressions should be considered a last resort for most
* string manipulation due to their high probablity of human error. Think hard
* about whether or not this solution is truly the last or best one available to
* you before employing it.
*
* This regular expression can be broken down into and explained in three parts:
* 1. A positive lookbehind group for the character preceding the selector.
* 2. A capture group for the selector itself.
* 3. A positive lookahead group for the character following the selector.
*
* ### First group (positive lookbehind) ###
* Requires that the character preceding tag be:
* - Start of file (^), or
* - Any form of whitespace (\s), or
* - A preceding rule's closing brace (}), or
* - A child (>), adjacent sibling (+), or general sibling (~) combinator
*
* ### Second group (capturing) ###
* Identifies the exact tag to search for.
*
* ### Third group (positive lookahead) ###
* Requires that the character following tag be:
* - A comma indicating the next rule (,), or
* - Any form of whitespace (\s), or
* - This rule's opening brace ({), or
* - An ID (#), class (.), or attribute ([) selector, or
* - A child (>), adjacent sibling (+), or general sibling (~) combinator, or
* - A pseudo-selector (:)
*
* Tests for this Regex are available at https://regex101.com/r/X1mqxs/3.
*/
function create_css_selector_regex(string $selector): string
{
return "/(?<=^|\s|}|>|\+|~)($selector)(?=,|\s|{|#|\.|\[|>|\+|~|:)/";
}
preg_replace(create_css_selector_regex('img'), 'custom-img');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment