2010-05-18 77 views
5

基本上,我想這一點:PHP函數組合CSS屬性/值分成幾個屬性

h2 { 
    font: bold 36px/2em "Times New Roman" 
} 

要這樣:

h2 { 
    font-size: 36px; 
    font-weight: bold; 
    line-height: 2em; 
    font-family: "Times New Roman" 
} 

和其他變化,當然。有沒有人知道這樣做的功能,所以我不必自己編寫代碼? :)

+2

我想有一個功能,做相反的.. – 2010-05-18 07:04:38

+1

@Alix Axel:是的更好的選擇和更合乎邏輯的:) – Sarfraz 2010-05-18 07:06:36

+0

是的,我希望它能夠管理兩種方式,當然:) – Sandman 2010-05-18 07:42:04

回答

3

CSS Font Shorthand Style Guide

我已經想出以下正則表達式:

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|.+?));?$ 

來自這些較小的正則表達式獲得:

$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|.+?))'; 

用法:

$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>'; 
} 

輸出:

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" 
) 

這意味着提取未驗證因爲它接受像XX-小的東西(即無效)。

要製作擴展版本,您可以使用preg_match()preg_replace(),但使用後者會更難以「忽略」未使用的聲明。

+0

謝謝!我會再看看這個! – Sandman 2010-05-20 11:27:15

+0

@Sandman:不客氣。 :) – 2010-05-20 11:33:48

0

在PHP中沒有這樣的功能。你可以創建一個這樣的函數 - 我會從一個包含[styleRuleName => [{有效屬性集}]]的地圖開始,爲每個你希望展開的速記選擇器。我想你會發現這是編碼的一個噩夢。在此基礎上CSS Shorthand for the Font Element

+1

當然沒有內置功能,我的意思是第三方功能。我可以自己編碼,但我不想:) – Sandman 2010-05-18 08:02:22

+0

也不知道這樣的第三方功能。大多數人都在關注綜合屬性,而不是擴展它們。 – Finbarr 2010-05-18 08:05:20