我想要实现的是基于'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”和“ Courier”。
这可能吗?
最佳答案
你可以试试这个。注释中的代码说明。如果您真的很感兴趣,我也可以解释这种模式。
$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)
关于php - PHP从字符串中提取css值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32993246/