将单引号与 preg_match 和 filter_var() 函数一起使用时出现问题
Problem in using single quotes with preg_match and filter_var() functions together
我 运行 遇到了 filter_var()、preg_match() 和单引号的问题。
我正在尝试清理和验证非法字符的姓氏。它适用于几乎所有东西,但显然像 O'Corner 这样包含单引号的姓氏会导致错误。
我的意思是 $errors[] = 'Please use only alphabets, period, dash and spaces in the last name.';每当我在用户输入字段中使用单引号时都会执行。
HTML代码:
<input type="text" class="form-control" name="last_name" id="last_name" placeholder="Enter last name" maxlength="40" required value="<?php if (isset($_POST['last_name'])) { echo htmlspecialchars($_POST['last_name'], ENT_QUOTES); } ?>" title="Alphabets, quotes, dash, spaces and max 40 characters" pattern="^[a-zA-Z][a-zA-Z' -]*$">
PHP代码:
$lname = filter_var($_POST['last_name'], FILTER_SANITIZE_STRING);
if (!empty($lname)) {
if (!preg_match("/^[a-zA-Z][a-zA-Z' -]*$/", $lname)) {
$errors[] = 'Please use only alphabets, period, dash and spaces in last name.';
} else if (strlen($lname) > 40) {
$errors[] = 'last name should not exceed 40 characters';
} else {
$lname = trim($lname);
}
} else {
$errors[] = 'Please enter your last name.';
}
我尝试用反斜杠转义正则表达式中的单引号。但这没有用。
如果我替换
$lname = filter_var($_POST['last_name'], FILTER_SANITIZE_STRING);
与
$lname = $_POST['lname'];
它工作正常。
但我仍然不确定使用包含单引号和 $lname = filter_var($_POST['last_name'], FILTER_SANITIZE_STRING) 的字符串有什么问题;使用 preg_match() 方法。
谁能帮帮我?
提前谢谢你。
您的问题来自对 filter_var 函数的特定调用将单引号 ' 编码到 html 实体 '
如果您在浏览器中打印 $lname 变量,它将呈现为常规单引号,但在其源代码中它不是引号而是提到的 html 实体。
我 运行 遇到了 filter_var()、preg_match() 和单引号的问题。
我正在尝试清理和验证非法字符的姓氏。它适用于几乎所有东西,但显然像 O'Corner 这样包含单引号的姓氏会导致错误。
我的意思是 $errors[] = 'Please use only alphabets, period, dash and spaces in the last name.';每当我在用户输入字段中使用单引号时都会执行。
HTML代码:
<input type="text" class="form-control" name="last_name" id="last_name" placeholder="Enter last name" maxlength="40" required value="<?php if (isset($_POST['last_name'])) { echo htmlspecialchars($_POST['last_name'], ENT_QUOTES); } ?>" title="Alphabets, quotes, dash, spaces and max 40 characters" pattern="^[a-zA-Z][a-zA-Z' -]*$">
PHP代码:
$lname = filter_var($_POST['last_name'], FILTER_SANITIZE_STRING);
if (!empty($lname)) {
if (!preg_match("/^[a-zA-Z][a-zA-Z' -]*$/", $lname)) {
$errors[] = 'Please use only alphabets, period, dash and spaces in last name.';
} else if (strlen($lname) > 40) {
$errors[] = 'last name should not exceed 40 characters';
} else {
$lname = trim($lname);
}
} else {
$errors[] = 'Please enter your last name.';
}
我尝试用反斜杠转义正则表达式中的单引号。但这没有用。
如果我替换
$lname = filter_var($_POST['last_name'], FILTER_SANITIZE_STRING);
与
$lname = $_POST['lname'];
它工作正常。
但我仍然不确定使用包含单引号和 $lname = filter_var($_POST['last_name'], FILTER_SANITIZE_STRING) 的字符串有什么问题;使用 preg_match() 方法。
谁能帮帮我?
提前谢谢你。
您的问题来自对 filter_var 函数的特定调用将单引号 ' 编码到 html 实体 '
如果您在浏览器中打印 $lname 变量,它将呈现为常规单引号,但在其源代码中它不是引号而是提到的 html 实体。