Hi Folks

I am trying to make a php form processing script. The form would have a large text area in it where the visitors could type a few paragraphs of text. I want this script to break the text from the form after 75 characters or if that is in the middle of a word, then break after completing that word. I also would like this script to insert a line number at the beginning of each line.

Does this sound possible? Any help is greatly appreciated.

Dani AI

Generated

As suggested, PHP's wordwrap is the right place to start. The snippet below shows a compact, practical pattern that preserves any manual paragraph breaks, wraps each input line at 75 characters without breaking words, adds a padded line number to every resulting line, and outputs safely for HTML.

<?php
// textarea name: 'comments'
$text = isset($_POST['comments']) ? $_POST['comments'] : '';

// normalize newlines and trim
$text = str_replace(array("\r\n", "\r"), "\n", $text);
$text = trim($text);

$wrappedLines = array();
foreach (explode("\n", $text) as $origLine) {
    if ($origLine === '') { // preserve blank lines
        $wrappedLines[] = '';
        continue;
    }
    // wrap at 75 chars, do not cut words
    $wrapped = wordwrap($origLine, 75, "\n", false);
    foreach (explode("\n", $wrapped) as $line) {
        $wrappedLines[] = $line;
    }
}

// add numbered prefixes, aligned to the total line count
$total = count($wrappedLines);
$digits = strlen((string)$total);
$numbered = '';
foreach ($wrappedLines as $i => $line) {
    $num = str_pad($i + 1, $digits, ' ', STR_PAD_LEFT);
    $numbered .= $num . ': ' . $line . "\n";
}

// safe HTML output; <pre> preserves spacing so numbers line up
echo '<pre>' . htmlspecialchars($numbered, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '</pre>';

Notes and troubleshooting

  • Blank lines in the original text are preserved. Adjust width (75) or numbering format as needed.
  • Very long unbroken tokens (long URLs or words) will exceed 75 chars because wordwrap(..., false) avoids cutting words; to force breaks use wordwrap(..., true) or insert soft breaks for URLs.
  • HTML spacing: use <pre> or white-space: pre so the padded numbers keep alignment; otherwise HTML will collapse the spaces.
  • UTF-8: wordwrap is byte-based and can miscount multibyte characters. For non-ASCII input, use mbstring-aware logic (split on whitespace with the u flag and assemble lines using mb_strlen) if exact character counts matter.
    This implements 's request (75-char wraps without mid-word breaks) and builds on 's suggestion.

Recommended Answers

All 2 Replies

Thanks for the info. This is what I was looking for. With some modification of my scrpt I think I can get it to work. Thanks alot.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.