我有一个遍历目录中所有CSS文件并查找@font-face
的函数。
如果发现任何@font-face
块,我想从中提取font-family
和font-weight
。
下面的代码是我目前所做的:
function get_local_fonts() {
$output = array();
$path_to_search = trailingslashit(get_template_directory());
foreach(glob_recursive($path_to_search . '*.css') as $file) {
$content = file_get_contents($file);
preg_match('/('@font-face)([^}]+)('})/', $content, $matches, PREG_OFFSET_CAPTURE);
if (!empty($matches)) {
preg_match('/(font-family:)([^;]*)/', $matches[2][0], $font_family, PREG_OFFSET_CAPTURE);
preg_match('/(font-weight:)([^;]*)/', $matches[2][0], $font_weight, PREG_OFFSET_CAPTURE);
$output[] = array(
'file_path' => $file,
'font-family' => trim($font_family[2][0]),
'font-weight' => array(trim($font_weight[2][0])),
);
}
}
return $output;
}
这个preg_match('/('@font-face)([^}]+)('})/', $content, $matches, PREG_OFFSET_CAPTURE);
返回所有包含@font-face { ... }
的CSS文件
我的函数可以很好地处理只有一个匹配@font-face
的CSS文件,但假设在单个CSS文件中有4个匹配@font-face,我的函数只添加其中一个。
例如(css文件内容):
@font-face
{
font-family: "din";
src: url("din-webfont.eot");
src: url("din-webfont.eot?#iefix") format("embedded-opentype"), url("din-webfont.woff") format("woff"), url("din-webfont.ttf") format("truetype");
font-weight: normal;
font-style: normal;
}
@font-face
{
font-family: "din";
src: url("din_bold-webfont.eot");
src: url("din_bold-webfont.eot?#iefix") format("embedded-opentype"), url("din_bold-webfont.woff") format("woff"), url("din_bold-webfont.ttf") format("truetype");
font-weight: bold;
font-style: normal;
}
我想得到这样的输出:Array
(
[0] => Array
(
[font-family] => 'din'
[font-weight] => Array
(
[0] => 'normal',
[1] => 'bold'
)
)
)
注意@font-face
可能与font-family
相同,但font-weight
不同。
结论:
如何循环遍历所有包含
@font-face {
font-family: something;
font-weight: something;
}
并从中提取font-family
和font-weight
?
使用如下代码:
$fontregex = '~@font-face[^}]*?font-family:'s*"([^"]+)"[^}]*?font-weight:'s*([^;]+);[^}]*?font-style:'s*([^;]+);~';
preg_match_all($fontregex, $mycss, $matches,PREG_SET_ORDER);
print_r($matches);
查看在线php演示底部的输出。您必须以适合您的方式将$matches
的结果扇到最终数组中。
当前的结构是:
Array
(
[0] => Array
(
[0] => @font-face
{
font-family: "din";
src: url("din-webfont.eot");
src: url("din-webfont.eot?#iefix") format("embedded-opentype"), url("din-webfont.woff") format("woff"), url("din-webfont.ttf") format("truetype");
font-weight: normal;
font-style: normal;
[1] => din
[2] => normal
[3] => normal
)
[1] => Array
(
[0] => @font-face
{
font-family: "din";
src: url("din_bold-webfont.eot");
src: url("din_bold-webfont.eot?#iefix") format("embedded-opentype"), url("din_bold-webfont.woff") format("woff"), url("din_bold-webfont.ttf") format("truetype");
font-weight: bold;
font-style: normal;
[1] => din
[2] => bold
[3] => normal
)
)