PHP Forme - messaggio di verifica e URL
Questa sezione descrive come verificare i nomi (nome), e-mail (spam), e gli URL.
PHP - verificare il nome
Il seguente codice sarà un modo semplice per rilevare se il nome del campo contiene lettere e gli spazi, se il valore del campo nome non è legittimo, emette un messaggio di errore:
$name = test_input($_POST["name"]); if (!preg_match("/^[a-zA-Z ]*$/",$name)) { $nameErr = "只允许字母和空格"; }
preg_match - Eseguire un match espressione regolare. sintassi: int preg_match (string $ pattern, string $ soggetto [, array $ partite [, int $ bandiere]]) Essere modello soggetto stringa di ricerca che corrisponde all'espressione regolare data contenuti. Se un match, poi i risultati della ricerca saranno riempiti. $ matches [0] conterrà il testo di tutto il modello corrisponde, $ matches [1] conterrà le prime parentesi sotto-modello catturati testo corrispondente, e così via. |
PHP - messaggio di verifica
Il seguente codice sarà un modo semplice per rilevare l'indirizzo e-mail è valido. Se l'indirizzo e-mail non è valido, l'uscita di un messaggio di errore:
$email = test_input($_POST["email"]); if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) { $emailErr = "非法邮箱格式"; }
PHP - convalidare l'URL
Il seguente codice rileverà l'URL è legittima (in seguito regolare funzionamento URL espressione contiene un trattino: "-"), se l'indirizzo URL non è valido, emette un messaggio di errore:
$website = test_input($_POST["website"]); if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) { $websiteErr = "非法的 URL 的地址"; }
PHP - verificare il nome, e-mail e URL
Codice come segue:
<?php // 定义变量并默认设置为空值 $nameErr = $emailErr = $genderErr = $websiteErr = ""; $name = $email = $gender = $comment = $website = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["name"])) { $nameErr = "Name is required"; } else { $name = test_input($_POST["name"]); // 检测名字是否只包含字母跟空格 if (!preg_match("/^[a-zA-Z ]*$/",$name)) { $nameErr = "只允许字母和空格"; } } if (empty($_POST["email"])) { $emailErr = "Email is required"; } else { $email = test_input($_POST["email"]); // 检测邮箱是否合法 if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) { $emailErr = "非法邮箱格式"; } } if (empty($_POST["website"])) { $website = ""; } else { $website = test_input($_POST["website"]); // 检测 URL 地址是否合法 if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) { $websiteErr = "非法的 URL 的地址"; } } if (empty($_POST["comment"])) { $comment = ""; } else { $comment = test_input($_POST["comment"]); } if (empty($_POST["gender"])) { $genderErr = "性别是必需的"; } else { $gender = test_input($_POST["gender"]); } } ?>