【问题标题】:Regular Expression, detecting right characters正则表达式,检测正确的字符
【发布时间】:2016-10-13 12:05:10
【问题描述】:

我创建了这个函数,它允许我发送一个字符串作为参数,然后我可以选择要检查英语、瑞典语或数字的 id。如果它包含除接受字符之外的任何内容,则函数将返回 false,否则返回 true。

示例:

$text = 'I like pancakes';  //This should return as true
if(isCharValid($text, 'english')) {
   die('returned as true');
}
else {
   die('returned as false');
}

但是,我无法让正则表达式检测 Id 想要检测的内容,您可以在代码的 cmets 中准确地看到我希望它检测的内容。

这是我的功能

function isCharValid($string, $type){ 
    if($type == 'english') { //String may contain A-Z, a-z, 0-9 and whitespace
        return !preg_match('/[^A-Za-z0-9\s]/', $string);
    }
    else if($type == 'swedish'){ //String may contain A-Ö,a-ö,0-9 and whitespace
        return !preg_match('/[^A-Za-z0-9åäöÅÄÖ\s]/', $string);
    }
    else if($type == 'number'){ //String may contain numbers 0-9, no WHITESPACES
        return !preg_match('/[^0-9]*$/', $string);
    }
    else {
        return false;
    }
}

【问题讨论】:

  • 它将始终返回false,因为您没有填写第二个参数$type。如果打开错误报告,您会看到警告。

标签: php regex expression whitespace


【解决方案1】:

致电:isCharValid($text,$type)

而不是isCharValid($text)

【讨论】:

  • 哦,对不起,我确实在我的代码中调用了这样的函数,在我的示例中只是一个脑残。谢谢指出:)
【解决方案2】:

您可能要求整个字符串应由这些字符组成,方法是用^ / $ 将模式括起来并将+ 量词添加到正字符类

function isCharValid($string, $type){ 
    if($type == 'english') { //String may contain A-Z, a-z, 0-9 and whitespace
        return preg_match('/^[A-Za-z0-9\s]+$/u', $string);
    }
    else if($type == 'swedish'){ //String may contain A-Ö,a-ö,0-9 and whitespace
        return preg_match('/^[A-Za-z0-9åäöÅÄÖ\s]+$/u', $string);
    }
    else if($type == 'number'){ //String may contain numbers 0-9, no WHITESPACES
        return preg_match('/^[0-9]+$/Du', $string);
    }
    else {
        return false;
    }
}

然后,使用

$text = 'I like pancakes';  //This should return as true
$type = "english";
if(isCharValid($text, $type)) {
   die(returned as true);
}
else {
   die(returned as false);
}

请注意,最好将/D 修饰符添加到最后一个数字正则表达式,以确保带有数字和末尾换行符 LF 符号的字符串无法匹配。

【讨论】:

  • 不,不是。正则表达式现在至少需要 1 个字符,并且只需要允许的字符。此外,/u 是必需的,因为文本是 Unicode。
  • 是的。他测试了集合之外的字符,然后用! 反转结果。所以这是同一个测试。
  • 唯一的区别是字符串中至少需要 1 个字符。目前尚不清楚这是一项要求。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-14
  • 2015-10-21
  • 2010-12-04
  • 2018-10-13
  • 1970-01-01
相关资源
最近更新 更多