I'm working on a recursive function that basically performs a simple 'word wrap' after a given number of characters. Given a string, an array and a the number of characters you want per line, this function should split up the string and return an array of 'lines'. It's not returning anything -- I believe that I'm having some trouble with keeping track of the array, related to passing by reference (or not).
Any help is greatly appreciated. ???
Function:
function makeWordWrap($text, $lines, $maxChars){
/* see if the text is longer than maxChars characters. If it is, find the space closest to character maxChars and split the string there */
/* do this again and again until we have an array of lines that are all maxChars or less characters long */
if(strlen($text) < $maxChars){
array_push($lines,$text);
return $lines;
}
/* we know the text is longer than 70, so figure out how many lines we are going to need */
$currentChunk = substr($text,0,$maxChars);
$lastSpace = strrpos($currentChunk," ");
$currentRow = substr($text,0,$lastSpace);
$text = substr($text,$lastSpace);
array_push($lines,$currentRow);
makeWordWrap($text,&$lines,$maxChars);
}
Test data:
$lines = array();
$txt = "The documentation for 'offset' is misleading. It says, offset may be specified to begin searching an arbitrary number of characters into the string. Negative values will stop searching at an arbitrary point prior to the end of the string. This is confusing if you think of strrpos as starting at the end of the string and working backwards. A better way to think of offset is: If offset is positive, then strrpos only operates on the part of the string from offset to the end. This will usually have the same results as not specifying an offset, unless the only occurences of needle are before offset (in which case specifying the offset won't find the needle). If offset is negative, then strrpos only operates on that many characters at the end of the string. If the needle is farther away from the end of the string, it won't be found. If, for example, you want to find the last space in a string before the 50th character, you'll need to do something like this.--------------------------";
print_r(makeWordWrap($txt,$lines,70));
function makeWordWrap($text, $lines, $maxChars){
/* see if the text is longer than maxChars characters. If it is, find the space closest to character maxChars and split the string there */
/* do this again and again until we have an array of lines that are all maxChars or less characters long */
if(strlen($text) < $maxChars){
array_push($lines,$text);
return $lines;
}
/* we know the text is longer than 70, so figure out how many lines we are going to need */
$currentChunk = substr($text,0,$maxChars);
$lastSpace = strrpos($currentChunk," ");
$currentRow = substr($text,0,$lastSpace);
$text = substr($text,$lastSpace);
array_push($lines,$currentRow);
makeWordWrap($text,&$lines,$maxChars);
}