Last active
March 4, 2022 18:23
-
-
Save norcross/b14fb2efc9b64eef3bc401e6e2e23645 to your computer and use it in GitHub Desktop.
test a string to see if it's a valid CSS unit, either by itself or by removing the integers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function confirm_css_unit( $string ) { | |
// First check for a null or allowed strings. | |
if ( empty( $string ) || null === $string || in_array( $string, [ 'auto', 'fit-content', 'inherit' ] ) ) { | |
return $string; | |
} | |
// Pull out the numerical portion. | |
$value = preg_replace( '~\D~', '', $string ); | |
// If we have no numbers at all, return 'auto' | |
// so hopefully it does not look weird. | |
if ( empty( $value ) ) { | |
return 'auto'; | |
} | |
// If the result matches our string, then it is only a number and | |
// we need to add the default px suffix and return it. | |
if ( $value === $string ) { | |
return $string . 'px'; | |
} | |
// Determine what our suffix is. | |
$suffix = str_replace( $value, '', $string ); | |
// If our suffix is one of the allowed ones, return the original string. | |
if ( in_array( $suffix, [ 'px', '%', 'ch', 'em', 'rem', 'pt', 'in', 'cm', 'mm', 'ex', 'pc', 'vh', 'vw', 'vmin', 'vmax' ] ) ) { | |
return $string; | |
} | |
// Since it wasn't one that we allow, return the numeric value with a px attached. | |
return $value . 'px'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment