開発環境
- OS X Lion - Apple(OS)
- Apache (Web Server)
- PHP (サーバーサイドプログラミング言語)
- TextWrangler(Text Editor) (BBEditの無料機能制限版、light版)
『初めてのPHP5』 (David Sklar 著、 桑村 潤 翻訳、 廣川 類 翻訳、 オライリー・ジャパン、2005年、ISBN978-4-87311-257-2)の付録 B (正規表現の基本)B.8(演習問題)2を解いてみる。
2.
PHPのコード(TextWrangler)
<?php
require 'formhelpers.php';
if(array_key_exists('_submit_check', $_POST)){
if($form_errors = validate_form()){
show_form($form_errors);
} else {
process_form();
}
} else {
show_form();
}
function show_form($errors = ''){
if($errors){
print "エラー: <ul><li>\n";
print implode("</li><li>", $errors);
print "</li></ul>\n";
}
print '<form method="POST" action="' . $_SERVER['PHP_SELF'] . '">';
print '<label>ユーザー名: ';
input_text('username', $_POST);
print '</label>';
input_submit('submit', 'submit');
print '<input type="hidden" name="_submit_check" value="1" />';
print "</form>";
}
function validate_form(){
$errors = array();
if(!strlen($_POST['username'])){
$errors[] = "ユーザー名を入力して下さい。";
} elseif (preg_match('/[^0-9A-Za-z]/', $_POST['username'])){
$errors[] = "ユーザー名には英数字のみ使用してください。";
}
return $errors;
}
function process_form(){
print "OK! ユーザー名: {$_POST['username']}<br />\n";
print "<a href='" . $_SERVER['PHP_SELF'] . "' />戻る</a>";
}
?>
HTMLソース
<form method="POST" action="/~kamimura/kamimura_blog/learning_php/sample77.php"><label>ユーザー名: <input type="text" name="username" value="" /></label><input type="submit" name="submit" value="submit"/><input type="hidden" name="_submit_check" value="1" /></form>
0 コメント:
コメントを投稿