加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > PHP > 正文

php 动态生成表单的简单示例

发布时间:2020-05-25 04:59:14 所属栏目:PHP 来源:互联网
导读:php 动态生成表单的简单示例

感兴趣的小伙伴,下面一起跟随脚本之家 jb51.cc的小编来看看吧。
经测试代码如下:


<?php
/**
 * 动态生成表单
 *
 * @param 
 * @arrange (512.笔记) jb51.cc
 **/
define('VALID_NOT_EMPTY','/.+/');
define('VALID_EMAIL',"/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?.)+(?:[a-z]{2,4}|museum|travel)$/i");
define('ALPHANUMERIC','/[^a-zA-Z0-9]/');

function displayForm($form,$function) {
$errors = array();

if (!empty($_POST))
{
// Validate form and post it
foreach ($form['fields'] as $field => $options)
{
if (is_array($options) && !empty($options['rule']))
{
// Remove all non-alphanumeric characters for the id/name
$name = preg_replace(ALPHANUMERIC,null,strtolower($field));

if (!preg_match($options['rule'],$_POST[$name]))
{
$errors[] = $field;
}
}
}

if (empty($errors)) {
call_user_func($function,$_POST);
}
}

if (!empty($errors) || empty($_POST))
{
//Display any errors
if (!empty($errors))
{
echo '<div class="errors">';
echo 'There was an error processing your form,please check the following fields and resubmit:';

echo '<ul>';
foreach($errors as $field)
{
echo sprintf('<li>%s</li>',$field);
}
echo '</ul>';
echo '</div>';
}

// Display the form
echo '<form method="post" action="#">';

foreach ($form['fields'] as $field => $options)
{
// PHP will make the array key the keys index if it's not an array
$name = is_array($options) ? $field : $options;

// Remove all non-alphanumeric characters for the id/name
$form_name = preg_replace(ALPHANUMERIC,strtolower($name));

if ($form['escape'] == true) $name = htmlspecialchars($name);

echo sprintf('<label for="%s">%s: </label>',$form_name,$name);

// Default is a standard text input
if (!is_array($options) || !isset($options['type']) || $options['type'] == 'text')
{
echo sprintf('<input type="text" id="%s" name="%s" value="%s" />',$_POST[$form_name]);
} elseif ($options['type'] == 'textarea') {
echo sprintf('<textarea id="%s" name="%s" cols="%s" rows="%s">%s</textarea>',$options['cols'],$options['rows'],$_POST[$form_name]);
} elseif ($options['type'] == 'select') {
echo sprintf('<select id="%s" name="%s">',$form_name);
foreach ($options['items'] as $item)
{
if ($form['escape'] == true) $item = htmlspecialchars($item);

echo sprintf('<option value="%s">%s</option>',$item,$item);
}
echo '</select>';
}
echo '<br />'. "n";
}

echo '<input type="submit" value="Send" />';
echo '</form>';
}
}
?>

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读