PHP用于将组合的CSS属性/值拆分为多个属性的函数

San*_*man 5 css php stylesheet

基本上,我想要这个:

h2 {
    font: bold 36px/2em "Times New Roman"
}
Run Code Online (Sandbox Code Playgroud)

对此:

h2 {
    font-size: 36px;
    font-weight: bold;
    line-height: 2em;
    font-family: "Times New Roman"
}
Run Code Online (Sandbox Code Playgroud)

当然还有其他变化.有没有人知道这样做的功能所以我不需要自己编码?:)

Ali*_*xel 3

基于Font 元素的 CSS 简写

CSS 字体速记样式指南

我想出了以下正则表达式:

font:(?:\s+(inherit|normal|italic|oblique))?(?:\s+(inherit|normal|small-caps))?(?:\s+(inherit|normal|bold(?:er)?|lighter|[1-9]00))?(?:\s+(\d+(?:%|px|em|pt)?|(?:x(?:x)?-)?(?:small|large)r?)|medium|inherit)(?:\/(\d+(?:%|px|em|pt)?|normal|inherit))?(?:\s+(inherit|default|.+?));?$
Run Code Online (Sandbox Code Playgroud)

从这些较小的正则表达式中获得:

$font['style'] = '(?:\s+(inherit|normal|italic|oblique))?';
$font['variant'] = '(?:\s+(inherit|normal|small-caps))?';
$font['weight'] = '(?:\s+(inherit|normal|bold(?:er)?|lighter|[1-9]00))?';
$font['size'] = '(?:\s+(\d+(?:%|px|em|pt)?|(?:x(?:x)?-)?(?:small|large)r?)|medium|inherit)';
$font['height'] = '(?:\/(\d+(?:%|px|em|pt)?|normal|inherit))?';
$font['family'] = '(?:\s+(inherit|default|.+?))';
Run Code Online (Sandbox Code Playgroud)

用法:

$regex = 'font:' . implode('', $font) . ';?$';    
$matches = array();
$shorthand = 'font: bold 36px/2em Arial, Verdana, "Times New Roman";';

if (preg_match('~' . $regex . '~i', $shorthand, $matches) > 0)
{
    echo '<pre>';    
    if (strlen($matches[1]) > 0) { // font-style is optional
        print_r('font-style: ' . $matches[1] . ';' . "\n");
    }

    if (strlen($matches[2]) > 0) { // font-variant is optional
        print_r('font-variant: ' . $matches[2] . ';' . "\n");
    }

    if (strlen($matches[3]) > 0) { // font-weight is optional
        print_r('font-weight: ' . $matches[3] . ';' . "\n");
    }

    print_r('font-size: ' . $matches[4] . ';' . "\n"); // required

    if (strlen($matches[5]) > 0) { // line-height is optional
        print_r('line-height: ' . $matches[5] . ';' . "\n");
    }

    print_r('font-family: ' . $matches[6] . ';' . "\n"); // required
    echo '</pre>';

    echo '<pre>';
    print_r($matches);
    echo '</pre>';
}
Run Code Online (Sandbox Code Playgroud)

输出:

font-weight: bold;
font-size: 36px;
line-height: 2em;
font-family: Arial, Verdana, "Times New Roman";

Array
(
    [0] => font: bold 36px/2em Arial, Verdana, "Times New Roman";
    [1] => 
    [2] => 
    [3] => bold
    [4] => 36px
    [5] => 2em
    [6] => Arial, Verdana, "Times New Roman"
)
Run Code Online (Sandbox Code Playgroud)

这是为了提取而不是验证,因为它接受像 xx-smaller 这样的东西(这是无效的)。

要制作扩展版本,您可以使用preg_match()preg_replace(),尽管使用后者将更难以“忽略”未使用的声明。