How to wrap a string into lines of width w in PHP

2 Answers

0 votes
/*
    This program wraps a string into lines of maximum width w.

    Method:
    - Split the input text into words using explode().
    - Build each line until adding another word would exceed the width.
    - When the limit is reached, store the line and begin a new one.
    - Uses PHP's string functions and arrays for clear and efficient processing.
*/

function wrap_text(string $text, int $w): string {
    $words = explode(' ', $text);   // Split text into words
    $line = '';
    $result = '';

    foreach ($words as $word) {

        // If line is empty, start it with the word
        if ($line === '') {
            $line = $word;
        }
        else {
            // Check if adding the next word exceeds width
            if (strlen($line) + 1 + strlen($word) <= $w) {
                $line .= ' ' . $word;
            } else {
                // Store the completed line
                $result .= $line . "\n";
                $line = $word;
            }
        }
    }

    // Add the final line
    if ($line !== '') {
        $result .= $line;
    }

    return $result;
}

$sample =
    "PHP provides useful built-in tools for handling strings. " .
    "This program demonstrates how to wrap text cleanly and efficiently.";

echo wrap_text($sample, 35);



/*
run:

PHP provides useful built-in tools
for handling strings. This program
demonstrates how to wrap text
cleanly and efficiently.

*/

 



answered 4 hours ago by avibootz
edited 3 hours ago by avibootz
0 votes
$text = "PHP provides useful built-in tools for handling strings. " .
        "This program demonstrates how to wrap text cleanly and efficiently.";
 
echo wordwrap($text, 35, "\n");


/*
run:

PHP provides useful built-in tools
for handling strings. This program
demonstrates how to wrap text
cleanly and efficiently.

*/

 



answered 3 hours ago by avibootz
...