0

我有以下代码。

$var1 = 'This is line1

         This is line2

         This is line3';

$var_arr = explode("\n", $var1); // or preg_split("/\n/", $var1); same
echo '<ul type = "disc" class="deal_data" >';
foreach($var_arr as $var1)
{                             
   echo '<li><p>'.$var1.'</p></li>';                                 
} 
echo '</ul>';
echo 'String Length:'.strlen($var_arr[1]);

它的输出是:

输出

第二个和第四个列表项如何获得不同于零的长度?

4

6 回答 6

1

I can see that there are two new lines in your $var1,

try this

explode("\n\n", $var1);

phpFiddle Demo

于 2013-06-13T10:53:30.103 回答
1

Add an explode delimeter,\r:

<?php
    $var1 = 'This is line1

             This is line2

             This is line3';

    $var_arr = explode("\n\r", $var1); // or preg_split("/\n/", $var1); same
    echo '<ul type = "disc" class="deal_data" >';
    foreach($var_arr as $var1)
    {
        echo '<li><p>'.$var1.'</p></li>';
    }
    echo '</ul>';
    echo 'String Length:'.strlen($var_arr[1]);
?>

The result is:

<ul type = "disc" class="deal_data" >
    <li>
        <p>This is line1</p>
    </li>
    <li>
        <p>This is line2</p>
    </li>
    <li>
        <p>This is line3</p>
    </li>
</ul>
String Length:24
于 2013-06-13T10:54:22.180 回答
1

That is because your input has five lines, two of which are empty:

$var1 = 'This is line1 /* Line 1 */
                       /* Line 2 */
         This is line2 /* Line 3 */
                       /* Line 4 */
         This is line3 /* Line 5 */';
于 2013-06-13T10:54:25.833 回答
0

Your text lines are separated by two newlines. You're exploding on one newline so you get array entries for the blank lines as well as the ones with text in.

Try

 $var_arr = explode("\n\n", $var1); 
于 2013-06-13T10:55:00.180 回答
0

for 命令的条件可能会帮助您...

$var1 = 'This is line1

         This is line2

         This is line3';

$var_arr = explode("\n", $var1); // or preg_split("/\n/", $var1); same
echo '<ul type = "disc" class="deal_data" >';
foreach($var_arr as $var1)
{                             
   if($var1!="")
       echo '<li><p>'.$var1.'</p></li>';                                 
} 
echo '</ul>';
echo 'String Length:'.strlen($var_arr[1]);
于 2013-06-13T10:55:47.100 回答
0

过滤和修剪你的数组:

$var1 = 'This is line1

         This is line2

         This is line3';

$var_arr = explode("\n", $var1);
$var_arr = array_filter(array_map("trim",$var_arr));

var_dump(array_values($var_arr));

输出

array (size=3)
  0 => string 'This is line1' (length=13)
  1 => string 'This is line2' (length=13)
  2 => string 'This is line3' (length=13)
于 2013-06-13T10:55:48.763 回答