Posted By

DaveChild on 09/09/09


Tagged

php typography


Versions (?)

PHP SoftHyphens Function


 / Published in: PHP
 

URL: http://www.addedbytes.com

This function will add soft hyphens after every 3rd character in words of over 10 characters. It will not leave fewer than three characters following a soft hyphen.

Known bugs: Adds soft hyphens to URLs and within HTML tags.

  1. function SoftHyphens($text) {
  2. $return = '';
  3. $words = preg_split('/([^A-Za-z0-9]+)/m', $text, 0, PREG_SPLIT_DELIM_CAPTURE);
  4. for ($j = 0, $wordCount = count($words); $j < $wordCount; $j++) {
  5. $wordLength = strlen($words[$j]);
  6. if ($wordLength > 10) {
  7. for ($i = 0; $i < $wordLength; $i++) {
  8. $return .= $words[$j][$i];
  9. if ((($i % 3) == 2) && ($i < ($wordLength - 3)) && ($i > 0)) {
  10. $return .= '&#173;';
  11. }
  12. }
  13. } else {
  14. $return .= $words[$j];
  15. }
  16. }
  17. return $return;
  18. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: DaveChild on September 9, 2009

Looks like this also has some issues with multi-byte characters. It counts them as several characters and adds a soft return in the middle of the character.

Posted By: stevephp on September 9, 2009

Thannks, I have strugged with long words in the past, and did not know of soft hyphens. Great function. Thanks.

You need to login to post a comment.