我使用 explode()
从特定目录中的字体文件名中提取字符串 ($style
),然后根据结果数组打印一些样式。如果字符串包含字母 n,结果将被截断。
服务器是运行PHP7.3的Ubuntu Bionic。在 if (in_array())
语句未能捕获字符串后,我添加了 print_r()
语句进行调试。就在那时,我看到字母 n
充当边界并截断输出。
字体名称均采用 $family
-$style
-webfont.woff(或 .woff2)格式,例如 merriweather-bold-webfont.woff
.
示例代码:
function my_fontload() {
// Locate font files
$font_path = get_stylesheet_directory_uri() . "/path/to/fonts/";
$files = glob(get_stylesheet_directory( __FILE__ ) . '/path/to/fonts/*.woff', GLOB_BRACE);
$suffix = '-webfont';
foreach($files as &$file) {
$font = basename($file, ".woff");
$font = chop($font,$suffix);
$family = explode("-", $font);
$family = $family[0];
$style = explode("-", $font);
echo '@font-face{font-family:\''.$family.'\';src:url('. esc_url(( $font_path).basename($file)).'2)format(\'woff2\'),url('.esc_url(( $font_path).basename($file)).')format(\'woff\');';
if (in_array('thin', $style) || in_array( 'hairline', $style)) {
// Do stuff
} elseif (in_array('regular', $style) || in_array( 'normal', $style)) {
// Do other stuff
} else {
// Do default stuff
}
// Other logic here
// debugging
print_r($style);
}
unset ($file);
}
预期结果:
(
[0] => merriweather
[1] => regular
)
(
[0] => merriweather
[1] => thin
)
(
[0] => merriweather
[1] => hairline
)
实际结果:
(
[0] => merriweather
[1] => regular
)
(
[0] => merriweather
[1] => thi
)
(
[0] => merriweather
[1] => hairli
)
就好像 n 被视为某种文字,例如换行符或其他东西。这是怎么回事?
最佳答案
首先,我建议将语法更改为:
list($family, $style) = explode('-', $font, 2);
看来您只想比较样式。那么您不需要 in_array
而只需使用 if
语句即可。
关于您的修剪问题:正如您在 chop documentation 中看到的那样,第二个参数表示要从字符串右侧删除哪些字母 - 您指定字母:-,w,e,b,f,o,n,t
因此,从最右边的字母开始 - 如果它是被修剪的字母之一 - 当遇到第一个字母时,它会停止 ->
因此,您会得到 thi
而不是 thin
,因为删除 n
但不是 i
。并且 hairli
而不是 hairline
,并且 n
和 e
均采用字母 -,w,e ,b,f,o,n,t
但不是 i
。
实例:3v4l .
如果您想要的只是删除后缀(我猜这就是您想要的),请使用:
substr($fonf, 0, - strlen('-webfont'));
已编辑:
这是您的代码示例:
$files = ['merriweather-regular-webfont.woff','merriweather-thin-webfont.woff','merriweather-hairline-webfont.woff'];
foreach($files as $file) {
$font = basename($file, ".woff"); // remove the file type
$font = str_replace('-webfont', '', $font); // remove the suffix
list($family, $style) = explode('-', $font, 2); // explode for 2 parts: family and style
echo "Family: $family and style: $style" . PHP_EOL;
if (in_array($style, ['thin', 'hairline'])) {
echo esc_html('font-weight:100;font-style:normal;');
} elseif (in_array($style, ['regular', 'normal'])) {
echo esc_html('font-weight:400;font-style:normal;');
} else {
echo esc_html('font-weight:400;font-style:normal;'); // Fallback
}
}
关于php - 使用chop和explode从文件路径中提取字符串,但结果数组不打印字母 "n",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56228409/