Code Snippet

Home » Code Snippets » PHP » Append Non-Breaking Space Between Last Two Words

Append Non-Breaking Space Between Last Two Words

<?php

function word_wrapper($text,$minWords = 3) {
       $return = $text;
       $arr = explode(' ',$text);
       if(count($arr) >= $minWords) {
               $arr[count($arr) - 2].= '&nbsp;'.$arr[count($arr) - 1];
               array_pop($arr);
               $return = implode(' ',$arr);
       }
       return $return;
}

?>

Reference URL

Subscribe to The Thread

  1. You can shorten this to:


    = $minWords)
    ? ' ' . array_pop($output)
    : ' ' . array_pop($output);
    $output = implode(' ',$output) . $widow;
    return $output;
    }
    ?>

  2. EXACTLY what I needed. Thanks!

  3. How to add non-breaking spaces to all words with less than 5 letters, not just 2 last?

  4. Is there any update to the css selectors for this fix to be 100% css solution? I have bugged W3c for ages about this — “Ah yes that’s a good idea” — and then they don’t add it to spec.

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~