我通常尽量避免使用preg_match()
, 因为我很少正确地理解模式。也许您可以尝试使用其他一些函数来进行验证。例如PHPctype_alnum() 用于名称字段和WPis_email() 用于电子邮件字段。就像这样,
if ( $_POST[\'submission_name\'] == \'\' ) {
$flag = 0;
echo "Please enter your name<br />";
} else if ( ! ctype_alnum( $_POST[\'submission_name\'] ) ) { // ctype_alnum returns TRUE if every character in text is either a letter or a digit, FALSE otherwise.
$flag = 0;
echo "Please enter a valid name<br />";
}
if ( $_POST[\'submission_email\'] == \'\' ) {
$flag = 0;
echo "Please enter your email address<br />";
} else if ( ! is_email( $_POST[\'submission_email\'] ) ) {
$flag = 0;
echo "Please enter a valid email address<br />";
}
此外,如果您想
wp_mail()
函数更具可读性,您可以这样做,
$name = sanitize_text_field( $_POST[\'submission_name\'] );
$email = sanitize_email( $_POST[\'submission_email\'] );
$subject = sprintf(
\'%s sent you a message from %s\',
$name,
get_option("blogname")
);
$message = sanitize_textarea_field( $_POST[\'submission_message\'] );
$from = sprintf(
"From: %s <%s>\\r\\n",
$name,
$email,
);
$reply_to .= sprintf(
"Reply-To: %s",
$email,
);
$headers = $from . $reply_to;
wp_mail(
get_option("admin_email"),
$subject,
$message,
$headers,
);