Skip to content

Instantly share code, notes, and snippets.

@kjbrum
Last active October 27, 2017 20:02
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 kjbrum/d4e9f31759520363dd9b17310a7df703 to your computer and use it in GitHub Desktop.
Save kjbrum/d4e9f31759520363dd9b17310a7df703 to your computer and use it in GitHub Desktop.
Make sure a string never has a widow.
<?php
/**
* Make sure a string never has a widow.
*
* @param string $text The string to dewidow
* @param int $min_words Minimum number of words to dewidow
* @return string The dewidowed string
*/
function dewidow( $text = '', $min_words = 3 ) {
$return = trim( $text );
$pos = strrpos( $return, ' ' );
// Check if a space exists
if ( $pos !== false && substr_count( $return, ' ' ) > ($min_words - 1) ) {
$return = substr_replace( $return, '&nbsp;', $pos, strlen( ' ' ) );
}
return $return;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment