PHP 从字符串中提取 css 值

标签 php css preg-match-all

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

 $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 从字符串中提取 css 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32993246/

相关文章:

javascript - 如何更改转换 :translate css rule according to the screen resolution?

php - 如何匹配整个 html 元素,无论里面有什么,就像浏览器一样?

php - 获取正则表达式中的所有匹配项

php - 在 PHP 中使用此正则表达式时遇到问题

php - 使用 PHP 更新 MySQL

php - 无法加载 mysqli 扩展

php - 如何使用带有唯一 ID 的 insert_batch

javascript - 如何使用 jquery ajax 和 php 上传文件(无需单击任何提交按钮)

css - 移动 CSS 未加载。我的代码正确吗?

javascript - 华丽的弹出式透明 png 为灰色