php:检查一个变量是否有has/lacks个特定的字符

php: check if a variable has/lacks particular characters

我实际上有两个问题,但它们几乎是一回事。

no1,我想使用 PHP 检查变量是否包含任何非正斜杠或数字的内容,我知道我可以为此使用 strpos() 但如果我做一些像

if (strpos($my_variable, "/")) {
    if (1 === preg_match('~[0-9]~', $string)) {
        //do something
    }
}

上面的代码首先 if 语句检查变量是否包含正斜杠,然后下一个检查变量是否包含字母,但是如果有人输入类似 'asdfgfds2345/' 作为他们的出生日期,它将通过,因为字符串包含正斜杠和数字,但我的 PHP 脚本会执行类似这样的操作

if(/*my_variable contains letters,special characters and any other thing that is not a number or a forward slash*/){
 do something}

下一个问题:我想用PHP检查一个变量是否包含任何不是小写字母、下划线或连字符的东西,我也是意识到我可以为此使用 strpos() 但是如果我不能继续做这样的事情就这样

if (strpos($my_variable, "/")) {
    //redirect
} else {
    if (strpos($my_variable, "?")) {
        //redirect
    } else {
        if (strpos($my_variable, "$")) {
            //redirect
        } else {
            //do something
        }
    }
}

如果我尝试执行上述操作,我将需要很长时间才能完成此页面 有什么方法可以做到这一点

$chars = "$""#""/""*";
if ($myvariable contains any of the letters in $char){
    //do something
}

我知道上面的代码在所有方面都是错误的,但我只是想向您展示我想要实现的目标

提前致谢

你可以试试这样的正则表达式:

if (preg_match('#[0-9/]#', $myvariable)) {
    //Do something
}

出生日期匹配:

如果要验证出生日期格式(假设[D]D/[M]M/YY[YY],日和月可能为个位数),可以按如下方式进行:

// This would match for any numbers:
if (preg_match('~^\d{1,2}/\d{1,2}/\d{2}(\d{2})?$~', $var)) {
    // proceed with valid date
} else {
    // protest much
}

这里我们使用 ^$ 锚点(用于 ^ 开头和 $ 主题结尾)来断言主题 $var必须 这个(而不是包括它):[D]D/[M]M/YY[YY],或 1-2 位数字,斜线,1-2 位数字,斜线,2 或 4 位数字(注意 (\d{2})? 可选匹配).

可以进一步调整正则表达式以匹配可接受的数字范围,但我相信现在就可以了。而是检查范围 post-process;您可能希望将其转换为时间戳(可能使用 strtotime)and/or SQL 日期时间,以便在任何情况下进一步使用。

您可以做的另一件方便的事情是立即捕获日期组件。在以下示例中,为清楚起见,我们使用命名捕获组:

if (preg_match('~^(?<day>\d{1,2})/(?<month>\d{1,2})/(?<year>\d{2}(\d{2})?)$~', $var, $date)) {
    var_dump($date); // see what we captured.
} else {
    // nothing to see here, except a protest.
}

注意包含匹配项的 $date 变量如何从条件检查行继续。您可以一步验证和解析,耶!结果(假设 20/02/1980 输入)在:

array(8) {
    [0] · string(10) "20/02/1980" // this is the complete subject
    ["day"] · string(2) "20"
    [1] · string(2) "20"
    ["month"] · string(2) "02"
    [2] · string(2) "02"
    ["year"] · string(4) "1980"
    [3] · string(4) "1980"
    [4] · string(2) "80" // this will only appear for 4-digit years
}

(非)匹配任何字符:

“我想使用 PHP 检查变量是否包含任何非小写字母、下划线或连字符的内容”。就这么简单:

if (preg_match('~[^a-z_-]~', $var)) {
    // matches something other than a-z, _ and -
} else {
    // $var only has acceptable characters
}

此处 ^ 运算符取反字符范围(仅在 [] 内,否则为主题开头)。如果你想做一个肯定的检查(例如 has #, &, X),只需 preg_match('~[#&X]~', $var)。花一点时间了解正则表达式是值得的。我仍然经常转向 RegularExpressions.Info 来刷新记忆或研究如何实现更复杂的表达式,但是那里还有很多其他资源。配对愉快,

这是一个简单使用的好用例strstr()

strstr — Find the first occurrence of a string

if (!strstr($a, '-')) {
  // No hyphen in $a
}