字符串和拆分然后插入到html表中

时间:2011-04-08 10:55:19

标签: php string

我想用(*)符号

分割这个字符串
$string="
How Many Papers*On My Table
How Many Mobiles*Your Brother have
";

我想拆分它们并将它们插入到像这样的html表中

<table border="1" width="100%" id="table1">
    <tr>
        <td>How Many Papers</td>
        <td>On My Table</td>
    </tr>
    <tr>
        <td>How Many Mobiles</td>
        <td>Your Brother have</td>
    </tr>
</table>

4 个答案:

答案 0 :(得分:1)

这里有两个问题:分成要用作<tr>的行,并拆分每行用作<td> s:

要获取每一行,您需要首先修剪原始字符串以摆脱前导和尾随换行(因此您不会在数组中以空行结束),然后您可以使用explode()来创建由换行符分隔的行数组:

$trimmedString = trim($string);
$lines = explode("\n", $trimmedString);

您也可以将这两个压缩成一行,以消除对临时$trimmedString变量的需求:

$lines = explode("\n", trim($string));

接下来,您希望使用foreach循环来迭代每一行。您将在此处创建表格行,然后再次使用explode()根据星号分隔行。您将使用另一个foreach循环来创建表数据元素:

foreach($lines as $line) {
  echo "<tr>";

  $elements = explode("*", $line);
  foreach($elements as $element) {
    echo "<td>" . $element . "</td>";
  }
  echo "</tr>";
}

答案 1 :(得分:0)

您可以使用explode()

$string="
How Many Papers*On My Table
How Many Mobiles*Your Brother have
";

// To split by newline
$tmp = explode("\n", $string); 
// To split by *
$data = array();
for($i = 0; $i < count($tmp); $i++) {
    $data[] = explode("*", $tmp[$i]);
}

答案 2 :(得分:0)

$array = explode("\n", (explode('*', $string)));

echo '<table border="1" width="100%" id="table1">';
foreach ($array as $row) {
  echo 'tr>'
  foreach ($row as $sr) {
    echo '<td>'.$sr.'</td>';
  }
  echo '</tr>';
}
echo '</table>';

答案 3 :(得分:0)

我更喜欢二维数组...

如此自然地我会采取类似的东西:

$line = array();
$line = explode( "\n" , $string );

$cell = array();

for ( $i = 0; != sizeof($line); $i++ ) {
    $cell[$i] = array();
    $cell[$i] = explode("*", $line[$i]);
}

所以你有一个像这样的二维数组:$ cell [linenumber] [cellnumber]

要在表格中打印单元格,我更喜欢嵌套的foreach循环:

foreach ( $cell as $row_number -> $row_array ) {
   echo "<tr>";
   foreach ( $row_array as $cell_number -> $cell_content ) {
       echo "<td>" . $cell_content . "</td>";
   }
   echo "</tr>";
}

请查看,如果出现问题或我犯了一些错误,请纠正我;)