Skip to content

Instantly share code, notes, and snippets.

@KruegerDesigns
Last active April 29, 2020 01:47
Show Gist options
  • Save KruegerDesigns/1d751f84bd4466695ee97b5fa7886418 to your computer and use it in GitHub Desktop.
Save KruegerDesigns/1d751f84bd4466695ee97b5fa7886418 to your computer and use it in GitHub Desktop.
<?php
// Why? After consolidating mutliple typekit accounts into one account,
// typekit renamed all our font-family CSS properties with a `-1` at the end of each font name.
//
// Story / Logic:
// If, string has no capitals, and string has no spaces,
// and string is not `serif` or `sans-serif`,
// then duplicate the true results and add `-1` to the end of each match...
// finally, add new font family name that matched to the beginning of the string of fonts.
$font_families = "source-sans-pro, 'verb', 'Source Sans Pro', sans-serif, serif"; // should match
$font_false = "'Arial'"; // should not match
$font_single = "'helvetica'"; // should match
function remove_quotes($text) {
// Regex to get any combination of quotes around font-family value
$regex = '(\'|")(.*?)(\'|")';
$text = preg_replace('/'.$regex.'/', "$2", trim($text));
return $text;
}
function typekit_match_conditionals($font) {
// get rid of outer spacing
$font_item = trim($font);
// eliminate capitalized font names, typekit wont refer to capitalize font names
$capitals = preg_match('/[A-Z]/', $font_item);
// eliminate spaces in font names, typekit wont refer to font names with spaces in them
$spaces = preg_match('/\s/',$font_item);
// `serif` and `sans-serif` are common fallbacks that do not rely on typekit, we ignore these font names
$serif = strpos($font_item, 'serif') == 0 && strlen($font_item) == 5 ? true : false;
$sans_serif = strpos($font_item, 'sans-serif') == 0 && strlen($font_item) == 10 ? true : false;
// Let's use the vars from above to match possible typekit references and return true or false
if ($spaces == 0 && $capitals == 0 && $sans_serif != true && $serif != true) {
$conditionals = true;
} else {
$conditionals = false;
}
return $conditionals;
}
function typekit_match($fonts) {
if (strpos($fonts, ',') !== false) {
$fonts_array = explode(',', $fonts);
foreach ($fonts_array as $font) {
// If any of the fonts are formatted like a typekit font, add `-1`
// then prepend the font back into the font family array
if (typekit_match_conditionals($font)) {
// remove quotes
$font = remove_quotes($font);
array_unshift($fonts_array, $font.'-1');
}
}
// Revert the font family array back into a comma separated list
$fonts_updated = trim(implode(",",$fonts_array));
return $fonts_updated;
} elseif (typekit_match_conditionals($fonts)) {
$fonts_updated = remove_quotes($fonts).'-1,'.$fonts;
return $fonts_updated;
} else {
return $fonts;
}
}
echo typekit_match($font_families)."<br>\r\n";
echo typekit_match($font_false)."<br>\r\n";
echo typekit_match($font_single);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment