Skip to content

Instantly share code, notes, and snippets.

@petertwise
Last active October 14, 2021 02:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petertwise/4007b7ff89f849f0b30eec57a2ed7509 to your computer and use it in GitHub Desktop.
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
<?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 ] .= '&nbsp;' . $words[ $word_count - 1 ];
array_pop( $words );
$text = implode( ' ', $words );
}
return $text;
}
@basscl
Copy link

basscl commented Oct 14, 2021

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment