automatically add soft hyphens to long words with PHP

Soft hyphens are optional hyphens that HTML will use when required to wrap a word to make sure it does not breach the space provided. This is a PHP function to add soft hyphens into words where required, and take the muscle word out of the equation.

function addSoftHyphen($word, $maxLen) {     
        if(strpos($word, "­") === false) {         
                if(strlen($word) > $maxLen) {             
                        $word = substr($word, 0, $maxLen)."­"
.substr($word, $maxLen);             
                        if(strlen(substr($word, strrpos($word, "­")+5))
>$maxLen) {                 
                                $word = addSoftHyphen($word, $maxLen);             
                        }         
                }     
        }     
        else {         
                if(strlen(substr($word, strrpos($word, "­")+5))>$maxLen) {             
                        $word = substr($word, 0, strrpos($word, "­")+5
+$maxLen)."­".substr($word, strrpos($word, "­")+5+$maxLen);         
                }         
                if(strlen(substr($word, strrpos($word, "­")+5))>$maxLen) {             
                        $word = addSoftHyphen($word, $maxLen);         
                }     
        }     
        return $word;
}

Just replace each occurrence of the excessively long word in question with a call to addSoftHyphen($word, $maxLen) and the word will be carefully broken and hyphenated as and when required without you needing to check each occurrence.

Advertisements

About Cameron
I'm a final year Computer Science/Information Systems major. Already finished my BA in Politics/Philosophy. I do web and software freelance on the side, while I finish studying. Hoping to be self-employed by the end of my degree, otherwise off into the real-world I go....

One Response to automatically add soft hyphens to long words with PHP

  1. mwilber says:

    Thank you for posting this. You just saved me a bunch of time.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: