PHP - 正则表达式匹配如果禁止命令

时间:2014-06-05 15:32:11

标签: php regex

我在PHP中有这样的正则表达式:

$msg = "ban:Joan24@Jump123" // Jump123 = password, Joan24 = user

if (preg_match($msg, "/ban:[A-Za-z0-9]@Jump123/")) // Not working -.-

如果有效,它应该返回true,但它不会,为什么,以及如何解决这个问题?

4 个答案:

答案 0 :(得分:1)

[^A-Za-z0-9]匹配除字母数字字符之外的所有内容。 /ban:[A-Za-z0-9]+@Jump123/"(没有#34; up-caret"在字符类中)将匹配您的输入消息。

答案 1 :(得分:1)

首先,preg_match是pattern,variable。 其次,模式必须介于简单'之间。 如果要使用具体的字符模式完成正则表达式,可以添加。*。 你的模式试图找不到角色。

    $msg = "ban:Joan24@Jump123"; // Jump123 = password, Joan24 = user
    if (preg_match('/ban:[A-Za-z0-9].*@Jump123/',$msg )) {
        print "TRUE";
    } else {
        print "FALSE";
    }
    $msg = "bOn:Joan24@Jump123"; // Jump123 = password, Joan24 = user
    if (preg_match('/ban:[A-Za-z0-9].*@Jump123/',$msg )) {
        print "TRUE";
    } else {
        print "FALSE";
    }
    $msg = "ban:1245@Jump123"; // Jump123 = password, Joan24 = user
    if (preg_match('/ban:[A-Za-z0-9].*@Jump123/',$msg )) {
        print "TRUE";
    } else {
        print "FALSE";
    }

答案 2 :(得分:1)

preg_match()的正确语法是:

int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )

此外,正则表达式中的character class [A-Za-z0-9]仅匹配1A Z 字符,{{ 1}}到az0,您需要在角色类之后放置quantifier

最终解决方案:(包含9修饰符,用于不区分大小写的匹配)

i

答案 3 :(得分:0)

This regex似乎可以解决这个问题,虽然我不认为自己是专家:

if (preg_match($msg, "/ban:[A-Za-z0-9]+@Jump123/")) // Note the '+' after the alphanumeric for 1 or more characters