PHP从字符串中提取css值

时间:2015-10-07 13:15:55

标签: php css preg-match-all

我想要实现的是将所有字体系列从基于' font-family'的字符串中收集到一个数组中,例如

 $string="
    Hi <span style=\"font-family: Arial \">text in Arial</span> 
    <br />
    A new line 
    <br />
    Hello again <span style=\"font-family:Courier ; font-size:12px;\"> text in courier font</span> 
  <br />
    Ready
    ";

    $array_fonts = preg_match_all(????);

所以$ array_fonts应该包含值'Arial&#39;和&#39; Courier&#39;。

这可能吗?

1 个答案:

答案 0 :(得分:0)

你可以尝试这个。注释中的代码中的说明。如果你真的很有兴趣,我也可以解释这个模式。

$string = ' Hi <span style="font-family: Arial ">text in Arial</span>
            <br />
            A new line
            <br />
            Hello again <span style="font-family:Courier ; font-size:12px;"> text in courier font</span>
            <br />
            Ready
';
//Initialize the result array
$fonts = array();
//Create a new DOMDocument and load the HTML string
$Dom = new \DOMDocument();
$Dom->loadHTML($string);
//Create a new DOMXPath
$xpath = new \DOMXPath($Dom);
//Get the spans
$spans = $xpath->query("//span");
//Iterate through spans
foreach ($spans as $span) {
    //Get the style attribute
    $style = $span->getAttribute('style');
    if ($style) {
        //If span has style, init an array for matches
        $matches = array();
        //Get the font family into the matches array
        preg_match('@font-family(\s*):(.*?)(\s?)("|;|$)@i', $style, $matches);
        if (!empty($matches[2])) {
            //If found font family, trim it, and put it into the result array
            $fonts[] = trim($matches[2]);
        }
    }
}
var_dump($fonts);

输出:

array (size=2)
   0 => string 'Arial' (length=5)
   1 => string 'Courier' (length=7)