是否可以在 if 语句中使用通配符?
我的代码:
*
= 通配符
if ($admin =='*@some.text.here') {
}
$admin
将是其中之一:
- xvilo@some.text.here
- bot!bot@some.text.here
- lakjsdflkjasdflkj@some.text.here
如果您不想使用正则表达式,fnmatch()
可能会很好地满足您的 [有限] 目的。它使用类似 shell 的通配符匹配字符串,就像您期望的那样。
if (fnmatch('*@some.text.here', $admin)) {
}
这是一个通配符功能。
当您*
只想使用时,我已经注释掉了.
(单字符匹配)。
这将允许您在整个过程中使用通配符:
*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()
您可以检查字符串是否以您期望的值结尾:
$suffix = '@some.text.here';
if (substr($admin, -strlen($suffix)) == $suffix) {
// Do something
}
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
}
检查一个字符串是否在另一个字符串中找到的最快方法是 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) {}