Skip to content

Instantly share code, notes, and snippets.

@josephbergdoll
Last active November 30, 2015 23:53
Show Gist options
  • Save josephbergdoll/6462519ef674dbc357a7 to your computer and use it in GitHub Desktop.
Save josephbergdoll/6462519ef674dbc357a7 to your computer and use it in GitHub Desktop.
Small PHP function to prevent orphans from occurring in digital typography. More on orphans, widows, and rags: http://www.fonts.com/content/learning/fontology/level-2/text-typography/rags-widows-orphans
<?php
// What are orphans?
// http://www.fonts.com/content/learning/fontology/level-2/text-typography/rags-widows-orphans
function noOrphans($str) {
$nbspStr = null;
if (strpos($str, '<p>') !== false) {
$paragraphs = explode('</p>', $str);
foreach($paragraphs as &$paragraph) {
$lastSpace = strrpos($paragraph, ' ');
$nbspParagraph = substr_replace($paragraph, '<span class="nbsp">&nbsp;</span>', $lastSpace, 1);
$nbspParagraph = $nbspParagraph . '</p>';
$paragraph = $nbspParagraph;
}
$nbspParagraphs = implode($paragraphs);
return $nbspParagraphs;
}
else {
$lastSpace = strrpos($str, ' ');
$nbspStr = substr_replace($str, '<span class="nbsp">&nbsp;</span>', $lastSpace, 1);
}
return $nbspStr;
};
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment