Grow your CSS skills. Land your dream job.

Last updated on:

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

Comments

  1. Permalink to comment#

    You can shorten this to:


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

  2. Permalink to comment#

    EXACTLY what I needed. Thanks!

  3. Ant

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

  4. Ang
    Permalink to comment#

    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.

  5. fabsn182
    Permalink to comment#

    Would be shorter I guess:

    return (substr_count($text, ” “) > 1 && substr_count($text, ” “) >= $minWords-1 ? substr_replace(strrpos($text, ” “) , ” “, $lastspace, 1) : $text;

    Maybe even

    return (substr_count($text, ” “) > 1 && str_word_count($text) >= $minWords ? substr_replace(strrpos($text, ” “) , ” “, $lastspace, 1) : $text;

    (both untestet)

  6. fabsn182
    Permalink to comment#

    Sorry. Second one should be

    return (str_word_count($text) >= $minWords ? substr_replace(strrpos($text, ” “) , “ ”, $lastspace, 1) : $text;

Leave a Comment

Posting Code

Markdown is supported in the comment area, so you can write inline code in backticks like `this` or multiline blocks of code in in triple backtick fences like ```this```. You don't need to escape code in backticks, Markdown does that for you.

Sadly, it's kind of broken. WordPress only accepts a subset of HTML in comments, which makes sense, because certainly some HTML can't be allowed, like <script> tags. But this stripping happens before the comment is processed by Markdown (via Jetpack). It seems to me that would be reversed, because after Markdown processes code in backticks, it's escaped, thus safe. If you think you can fix this issue, get in touch!

If you need to make sure the code (typically HTML) you post absolutely posts correctly, escape it and put it within <pre><code> tags.

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".