5

是否可以在 if 语句中使用通配符?

我的代码:

*= 通配符

if ($admin =='*@some.text.here') {

}

$admin将是其中之一:

  • xvilo@some.text.here
  • bot!bot@some.text.here
  • lakjsdflkjasdflkj@some.text.here
4

5 回答 5

14

如果您不想使用正则表达式,fnmatch()可能会很好地满足您的 [有限] 目的。它使用类似 shell 的通配符匹配字符串,就像您期望的那样。

if (fnmatch('*@some.text.here', $admin)) {

}
于 2013-03-14T16:32:40.250 回答
3

这是一个通配符功能。
当您*只想使用时,我已经注释掉了.(单字符匹配)。

这将允许您在整个过程中使用通配符:
*xxx- 以“xxx”结尾
xxx*- 以“xxx”
xx*zz开头 - 以“xx”开头并以“zz”结尾
*xx*- 中间有“xx”

function wildcard_match($pattern, $subject)
{
    $pattern='/^'.preg_quote($pattern).'$/';
    $pattern=str_replace('\*', '.*', $pattern);
    //$pattern=str_replace('\.', '.', $pattern);
    if(!preg_match($pattern, $subject, $regs)) return false;
    return true;
}
if (wildcard_match('*@some.text.here', $admin)) {

}

但我建议自己学习使用正则表达式preg_match()

于 2013-03-14T16:12:31.153 回答
3

您可以检查字符串是否以您期望的值结尾:

$suffix = '@some.text.here';

if (substr($admin, -strlen($suffix)) == $suffix) {
    // Do something
}
于 2013-03-14T15:46:08.063 回答
1
if (strstr ($admin,"@some.text.here")) {

}

使用 strstr() 它会做你想做的事或如指出 strstr()

或者你可以使用类似这样的 strpos

$pos = strrpos($mystring, "@some.text.here");
if ($pos === false) { // note: three equal signs
    // not found...
} else {
    //found
}

或从头开始(我认为没有测试过)

$checkstring = "@some.text.here";
$pos = strrpos($mystring, $checkstring, -(strlen($checkstring)));
if ($pos === false) { // note: three equal signs
    // not found...
} else {
    //found
}
于 2013-03-14T15:45:08.143 回答
0

检查一个字符串是否在另一个字符串中找到的最快方法是 strpos():

if (strpos($admin, '@some.test.here') !== false) { }

如果您需要确定 @some.text.here 出现在最后,您需要使用 substr_compare() 代替。

if (substr_compare($str, $test, strlen($str)-strlen($test), strlen($test)) === 0) {}
于 2013-03-14T15:47:02.517 回答