是否可以在if语句中使用通配符?
我的代码:
*
=通配符
if ($admin =='*@some.text.here') {
}
$admin
将是其中之一:
- xvilo@some.text.here
- 机器人!bot@some.text.here
- lakjsdflkjasdflkj@some.text.here
如果您不想使用正则表达式,fnmatch()
可能会很好地满足这个[有限]的目的。它使用类似shell的通配符来匹配字符串,正如您所期望的那样。
if (fnmatch('*@some.text.here', $admin)) {
}
您可以检查字符串是否以您期望的值结尾:
$suffix = '@some.text.here';
if (substr($admin, -strlen($suffix)) == $suffix) {
// Do something
}
这里有一个通配符函数
由于您希望只使用*
,所以我已经注释掉了.
(单字符匹配(。
这将允许您在以下各处使用通配符:*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()
的正则表达式。
if (strstr ($admin,"@some.text.here")) {
}
使用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出现在末尾,则需要使用substra_compare((。
if (substr_compare($str, $test, strlen($str)-strlen($test), strlen($test)) === 0) {}