Numbering per line

[b]code[/b]

<?php
$myVar='Tom live in New York. He is an American.
Chu live in Seoul. He is a Korean.
Paul live in Paris. He is a French.
Danaki live in Tokyo. He is a Japanese.';

echo $myVar

$myVar1=nl2br($myVar);

echo $myVar1;
?>

I have the code above.

The result of $myVar is in the below.

[b]$myVar result[/b]
Tom live in New York. He is an American.
Chu live in Seoul. He is a Korean.
Paul live in Paris. He is a French.
Danaki live in Tokyo. He is a Japanese.

The result of $myVar1 is in the below.

[b]$myVar1 result[/b]
Tom live in New York. He is an American.[COLOR="#FF0000"]<br />[/COLOR]
Chu live in Seoul. He is a Korean.[COLOR="#FF0000"]<br />[/COLOR]
Paul live in Paris. He is a French.[COLOR="#FF0000"]<br />[/COLOR]
Danaki live in Tokyo. He is a Japanese.

I like to insert numbering per every line break.
My target result is in the below.

[b]target result[/b]
[COLOR="#FF0000"]1[/COLOR]Tom live in New York. He is an American.[COLOR="#FF0000"]<br />[/COLOR]
[COLOR="#FF0000"]2[/COLOR]Chu live in Seoul. He is a Korean.[COLOR="#FF0000"]<br />[/COLOR]
[COLOR="#FF0000"]3[/COLOR]Paul live in Paris. He is a French.[COLOR="#FF0000"]<br />[/COLOR]
[COLOR="#FF0000"]4[/COLOR]Danaki live in Tokyo. He is a Japanese

How can I get my target result above?

Try this:


$myVar='Tom live in New York. He is an American.
Chu live in Seoul. He is a Korean.
Paul live in Paris. He is a French.
Danaki live in Tokyo. He is a Japanese.';

$myVar2 = "";

foreach (preg_split('/[\\r\
]+/', $myVar) as $i => $line) {
	$myVar2 .= ($i + 1) . $line . "<br />\
";
}

echo $myVar2;

Pretty much the same as LJ above


$myVar='Tom live in New York. He is an American.
Chu live in Seoul. 
He is a Korean.
Paul live in Paris. He is a French.
Danaki live in Tokyo. He is a Japanese.';

$i=1;

$spikeVar = explode("\
", $myVar);

foreach($spikeVar as $regurg) {   
   echo $i++ . ' '. $regurg .'<br />';   
}

I used preg_split so that the code works the same regardless of the type of line endings. If the OP uses Windows (\r
) line endings then the explode will leave some stray \r characters in the output. Probably they won’t do any harm in HTML but in other cases might cause some hidden surprises!