Home >Backend Development >PHP Tutorial >PHP regular expression combat: matching CSS styles

PHP regular expression combat: matching CSS styles

王林
王林Original
2023-06-22 18:31:40961browse

In web development, CSS style sheets are an indispensable part, which can conveniently set styles for HTML elements. However, sometimes we need to extract specific styles from a large CSS file, then we can use PHP's regular expression function for matching. This article introduces how to use PHP regular expressions to match CSS styles in practice.

Let’s first take a look at the basic structure of CSS styles:

selector {
    property: value;
    property: value;
}

A basic CSS style consists of a selector and a set of attribute-value pairs. The selector specifies the HTML element to which the style should be applied, and the attribute-value pair is the specific style setting. In CSS, attributes and values ​​are separated by a colon ":", and each attribute-value pair is separated by a semicolon ";".

Next, we use an example to illustrate how to use PHP regular expressions to match CSS styles.

Suppose we have a CSS file (style.css) that contains the following styles:

h1 {
    font-size: 24px;
    font-family: Arial, sans-serif;
    color: #333;
}

p {
    font-size: 16px;
    font-family: Helvetica, Arial, sans-serif;
    line-height: 1.4;
    color: #666;
}

.btn {
    display: inline-block;
    padding: 10px 20px;
    border: none;
    border-radius: 4px;
    font-size: 16px;
    font-weight: bold;
    text-transform: uppercase;
    background-color: #f00;
    color: #fff;
}

Now, we need to extract all the styles of the ".btn" category from this file. You can use PHP's file_get_contents function to read the entire file content, and then use the preg_match_all function to match.

// 读取样式文件内容
$css = file_get_contents('style.css');

// 匹配样式
$pattern = '/.btns*{([^}]+)}/';
preg_match_all($pattern, $css, $matches);

// 输出匹配结果
print_r($matches[0]);

In the above code, first use the file_get_contents function to read the content of the style file and save the content in the variable $css. Then, use the preg_match_all function to match the style, and the constructed regular expression is ".btns*{(1 )}":

  • ". btn" matches the selector of the ".btn" category;
  • "s*" matches 0 or more whitespace characters;
  • "{(1 )}" matches a set of attribute-value pairs within curly brackets, where "1" means matching any character except the right curly bracket "}", plus The brackets "()" indicate that the matching results are saved in the $matches array.

Finally, output the matching results.

Run the above code, the results are as follows:

Array
(
    [0] => .btn {
    display: inline-block;
    padding: 10px 20px;
    border: none;
    border-radius: 4px;
    font-size: 16px;
    font-weight: bold;
    text-transform: uppercase;
    background-color: #f00;
    color: #fff;
}
)

As can be seen from the results, the regular expression successfully matched the style of the ".btn" category and returned the entire style block.

Of course, we can also further extract the attribute-value pairs.

// 读取样式文件内容
$css = file_get_contents('style.css');

// 匹配样式
$pattern = '/.btns*{([^}]+)}/';
preg_match_all($pattern, $css, $matches);

// 提取属性-值对
$pattern = '/([a-z-]+)s*:s*([^;]+);/';
foreach ($matches[1] as $block) {
    preg_match_all($pattern, $block, $props);
    print_r($props);
}

In the above code, we use another regular expression "([a-z-] )s:s(2 ) ;" to match attribute-value pairs:

  • "([a-z-] )" matches attribute names, where "[a-z-]" means matching characters consisting of lowercase letters and dashes "-" String, plus brackets "()" means to save the matching result in the first element in the $props array;
  • "s:s" matches between the attribute name and the attribute value The colon ":" can contain 0 or more blank characters in the middle;
  • "(2)" matches the attribute value, where "2" means matching any character except semicolon ";", adding brackets "()" means saving the matching result in the second element in the $props array;
  • The last semicolon ";" is used to ignore the closing brace "}" at the end of the style block.

Here we use a foreach loop to traverse all style blocks, extract the attribute-value pairs of each style block, and output the results.

Run the above code, the results are as follows:

Array
(
    [0] => Array
        (
            [0] => display: inline-block;
            [1] => padding: 10px 20px;
            [2] => border: none;
            [3] => border-radius: 4px;
            [4] => font-size: 16px;
            [5] => font-weight: bold;
            [6] => text-transform: uppercase;
            [7] => background-color: #f00;
            [8] => color: #fff;
        )

    [1] => Array
        (
            [0] => display
            [1] => padding
            [2] => border
            [3] => border-radius
            [4] => font-size
            [5] => font-weight
            [6] => text-transform
            [7] => background-color
            [8] => color
        )

    [2] => Array
        (
            [0] => inline-block
            [1] => 10px 20px
            [2] => none
            [3] => 4px
            [4] => 16px
            [5] => bold
            [6] => uppercase
            [7] => #f00
            [8] => #fff
        )

)

As can be seen from the results, we successfully extracted the attribute-value pairs in the style of the ".btn" category, and put the results according to The attribute name and attribute value are stored in the first and second elements of the $props array respectively.

Through the above examples, we have learned how to use PHP regular expressions to match CSS styles. I believe that everyone has mastered the basic skills of how to construct regular expressions, and perform style matching and attribute extraction. In actual development, we can also perform more complex matching and extraction operations as needed to meet the needs of different style processing.


  1. }
  2. ;

The above is the detailed content of PHP regular expression combat: matching CSS styles. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn