Last active
October 14, 2021 02:52
-
-
Save petertwise/4007b7ff89f849f0b30eec57a2ed7509 to your computer and use it in GitHub Desktop.
PHP widow buster function - eliminate a single word wrapping to a new line
This file contains 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 widow_buster( $text, $min_words = 3, $max_chars = 16 ) { | |
$words = explode( ' ', $text ); | |
$word_count = count( $words ); | |
$char_length = strlen( $words[ $word_count - 2 ] ) + strlen( $words[ $word_count - 1 ] ); | |
// if our minimum word count and maximum character count are met, | |
// join the last two words with a non-breaking space | |
if ( $word_count >= $min_words && $char_length <= $max_chars ) { | |
$words[ $word_count - 2 ] .= ' ' . $words[ $word_count - 1 ]; | |
array_pop( $words ); | |
$text = implode( ' ', $words ); | |
} | |
return $text; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
NB need to abort if $word_count < $min_words before line 8, otherwise $words[ $word_count - 2 ] and $words[ $word_count - 1 ] don't exist, so php throws an error