Skip to content

Instantly share code, notes, and snippets.

@danielholmstrom
Last active December 25, 2015 21:29
Show Gist options
  • Save danielholmstrom/7042331 to your computer and use it in GitHub Desktop.
Save danielholmstrom/7042331 to your computer and use it in GitHub Desktop.
<?php
/** Prepare a string for use with wordwrap by hyphenate words longer that $width
*
* Example:
* echo prep("1 12 123 1234 12345 123456 1234567 12345678", 4), PHP_EOL;
* Outputs:
* 1 12 123 123-4 123-45 123-456 123-4567 123-456-78
* XXX: DO NOT USE THIS UNLESS YOU KNOW YOU CAN(See for example preg_quote()).
*/
function prep($str, $width=72) {
$old = null;
$new = $str;
$limit = $width - 1;
while ($old !== $new) {
$old = $new;
$new = preg_replace("/([a-z0-9]{{$limit},{$limit}})([a-z0-9]{2,})/i", "\\1-\\2", $old);
}
return $new;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment