Skip to content

Instantly share code, notes, and snippets.

@christoferd
Last active January 2, 2016 13:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christoferd/8312445 to your computer and use it in GitHub Desktop.
Save christoferd/8312445 to your computer and use it in GitHub Desktop.
String/Text Word Wrap at a certain character. First created to wrap a long CSV list.
function wordWrapAtCharacter($str, $minWidth = 200, $char = ',', $lineBreak = "\n")
{
// prev pos
$marker = 0;
// char pos
$pos = false;
if($minWidth+$marker < strlen($str))
{
$pos = strpos($str,$char,$minWidth+$marker);
}
// return string
$ret = '';
while($pos !== false)
{
// add sub string to return string
$pos += strlen($char);
$ret .= substr($str,$marker,($pos-$marker)).$lineBreak;
$marker = $pos;
// char pos
if(($minWidth+$marker) < strlen($str))
{
$pos = strpos($str,$char,$minWidth+$marker);
}
else {
$pos = false;
}
}
// add final piece
$ret .= substr($str,$marker).$lineBreak;
return $ret;
}
// Test
function test_wordWrapAtCharacter()
{
echo '<pre>';
$input = '10010,10020,31000,15000,10020,10300,10200,3600,1040,1510,24810,342000,50250,10000,120825,12535,174900,65040,10010,10020,31000,15000,10020,10300,10200,3600,1040,1510,24810,342000,50250,10000,120825,12535,174900,65040,10010,10020,31000,15000,10020,10300,10200,3600,1040,1510,24810,342000,50250,10000,120825,12535,174900,65040,10010,10020,31000,15000,10020,10300,10200,3600,1040,1510,24810,342000,50250,10000,120825,12535,174900,65040,10010,10020,31000,15000,10020,10300,10200,3600,1040,1510,24810,342000,50250,10000,120825,12535,174900,65040';
echo "\nInput: $input";
echo "\nOutput: \n".wordWrapAtCharacter($input,80,',');
echo "\n\n - done.";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment