Correcting Typographic Widows with  PHP

Automatically fix typographic widows to avoid a single hanging word on its own line.

A typographic widow is a word alone on its own line, and it usually doesn’t look good. On the web, it often happens with headings, and there isn’t a clean way to correct it with CSS alone. There are some JavaScript approaches, but I’ve found PHP to be best because it avoids any shifting layouts caused by using JS.

Typographic Widow Example

PHP

The following function will replace the last space in a sentence ($string) with a   character. This forces the last two words to stay together on the same line. If the last word needs to move to the next line, the last two words will be moved. This fixes typographic widows, avoiding any single word from being display on it’s own line. I typically use it in HTML heading elements.

/**
 * Avoid Typography Widows
 *
 * @param mixed $string
 */
function kevinlearynet_widowfix( $string ) {

  // Must contain a space
  if ( ! strstr($string, ' ') ) return;

  $words = explode( ' ', $string );
  $last = array_key_last( $words );
  $text = '';

  foreach ( $words as $index => $word ) {
    if ( 0 === $index ) {
      $text .= $word;
    } elseif ( $index === $last ) {
      $text .= '<span class="widowfix-on">&nbsp;</span>';
      $text .= '<span class="widowfix-off"> </span>';
      $text .= $word;
    } else {
      $text .= " {$word}";
    }
  }

  return $text;
}

CSS

The function wraps modified text with span elements for responsive styling. I’ve found that it’s usually best to disable this on mobile screens, so the classes added to each allow for responsively enabling or disabling the functionality on smaller screens.

@media screen and (max-width: 767px) {
  .widowfix-on {
    display: none;
  }
  .widowfix-off {
    display: block;
  }
}
@media screen and (min-width: 768px) {
  .widowfix-on {
    display: block;
  }
  .widowfix-off {
    display: none;
  }
}

Adjust as you see fit, of course, but it is a good idea to test and check any use of this on small screens. Forcing two larger words onto their own line in a large font-size can often lead to issues.

Meet the Author

Kevin Leary, WordPress Consultant

I'm a custom WordPress web developer and analytics consultant in Boston, MA with 17 years of experience building websites and applications. View a portfolio of my work or request an estimate for your next project.