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;
}


?>

Comments

  1. User Avatar
    Bill Brown
    Permalink to comment#

    You can shorten this to:


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

  2. User Avatar
    Josh L
    Permalink to comment#

    EXACTLY what I needed. Thanks!

  3. User Avatar
    Ant

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

  4. User Avatar
    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. User Avatar
    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. User Avatar
    fabsn182
    Permalink to comment#

    Sorry. Second one should be

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

  7. User Avatar
    David Condrey
    Permalink to comment#

    $text = preg_replace( '|([^\s])\s+([^\s]+)\s*$|', '$1&nbsp;$2', $text);

Submit a Comment

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-closeicon-emailicon-linkicon-logo-staricon-menuicon-searchicon-staricon-tag