首页 > 解决方案 > php将字符串拆分为html形式

问题描述

我以以下格式将字符串存储在 mysql 数据库中:

 $row["actions"]=   Add&&Remove&&Replace&&Change&&

例如,我需要将其中的每一个拼接成一个复选框 html 表单

  while{
    echo  $row["actions"];
     //this would be the string to cut up

     }
for each before && as cut {
     <form action="" method="post">
 //name would be add
      <input type="checkbox" name='$cut[0]' value="Bike"> I have a bike<br>
//name would be Remove
 <input type="checkbox" name='$cut[1]' value="Bike"> I have a bike<br>
//name would be replace
   <input type="checkbox" name='$cut[2]' value="Bike"> I have a bike<br>
      <input type="submit" value="Submit">
    </form>}

标签: phparraysstring

解决方案


为什么你不能只使用简单的检查,因为你有预定义的动作?

// If you have "Add" in your string, then print needed string
if (strpos( $row["actions"], 'Add') !== false) {
    echo "<input type=\"checkbox\" name='Add' value=\"Bike\"> I have a bike<br>"
}
//... and so on`

如果你真的需要拆分和迭代你的值,那么看看explode函数,它就是这样做的。文档

目前还不清楚您要达到的目标。正如评论中已经指出的那样,您不应该:

  • 在数据库的一行中存储多个值 \ 在一个变量中
  • 有用于互斥操作的复选框 (?)。可能你想要这里的单选按钮。

另请注意,您的代码不是有效的 PHP 代码。你不能像这样混合 HTML 和 PHP。因此,您需要关闭 PHP 标记 like<?php $a=1; ?> <a href="google.com">HTML goes here</a>或 doechoprintecho "<a href=\"google.com\">Some HTML</a>";


推荐阅读