Skip to content

Instantly share code, notes, and snippets.

@derekaug
Created December 22, 2015 15:47
Show Gist options
  • Save derekaug/b829247a5ee6dc660dd4 to your computer and use it in GitHub Desktop.
Save derekaug/b829247a5ee6dc660dd4 to your computer and use it in GitHub Desktop.
takes a string (expecting no html) and adds   to it to prevent widows
<?php
/**
* replaces the last space in a block of text with a &nbsp; to help prevent widows
* @param $string
* @return string
*/
function no_widow($string)
{
$string = trim($string);
$line_split = preg_split('`\n`', $string);
$rvalue = '';
if (count($line_split) > 1) {
foreach ($line_split as $split) {
$rvalue .= no_widow($split) . "\n";
}
} else {
$split = preg_split('`[\s]+`', $string);
$last = array_pop($split);
if (count($split) > 0) {
$rvalue .= implode(' ', $split) . '&nbsp;';
}
$rvalue .= $last;
}
return $rvalue;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment