Page 1 of 1

Processing String or Text with Line Numbering

Posted: Fri Feb 05, 2010 7:25 pm
by devarishi
Hi,

Kindly consider this code fragment:

Code: Select all

$message = $_REQUEST['txtMessage'];
It is clear that the variable $message would contain whatever data / text was passed through the text field txtMessage.

Let the contents of the textarea field named txtMessage look like this:

Code: Select all

Line Number One
Line Number Two
Line Number Three
Note: The above text essentially contains a line break at the end of each line.

Now I want to process the contents of $message in a way as to put a Line Number at the start of each line.

So, the final output would looke like this:

Code: Select all

 
1# Line Number One
2# Line Number Two
3# Line Number Three
 
How to accomplish it- the Line Numbering Thing?

Note: In fact, the contents of the $message are being emailed and I want to format the contents as shown above. Moreover, the text in the textarea field could be very lengthy.

Re: Processing String or Text with Line Numbering

Posted: Fri Feb 05, 2010 7:41 pm
by AbraCadaver
One way:

Code: Select all

$lines = explode("\n", $message);
 
$i = 0;
foreach($lines as &$line) {
    $i++;
    $line = "$i# $line";
}
 
$message = implode("\n", $lines);

Re: Processing String or Text with Line Numbering

Posted: Sat Feb 06, 2010 2:29 pm
by devarishi
Hi AbraCadaver!

Thanks for your support! What you have described works fine! I have modified the code as given below:

Code: Select all

<?php
 
$i = 0;
 
# This function sets number at the start of each line within the piece of a text and returns the numbered string.
function setLineNumber($SomeText) {
    $lines = explode("\n", $SomeText);
 
    global $i;
    foreach($lines as &$line) {
        $i++;
        $line = "$i# $line";
    }
 
    $SomeText = implode("\n", $lines);
    return($SomeText);
}
 
 
$message = $_REQUEST["txtData"];
 
$message = trim($message);
$message = nl2br($message);
 
$message = setLineNumber($message);
 
echo "<br /><br />";
echo $message;
 
echo "<br><br>Total: " . $i;
 
?>

Well, that is just for testing only. The real challenge is that the variable $message would hold the values of 8 textarea fields containing HTML Tags as they all would be packed in the Body of the Email Message.

Well, I will be able to perform that task easily as we have already devised the core function.

Thanks again!