Php 使用shell样式的通配符匹配字符串(例如*)
是否可以在if语句中使用通配符 我的代码:Php 使用shell样式的通配符匹配字符串(例如*),php,string,wildcard,Php,String,Wildcard,是否可以在if语句中使用通配符 我的代码: *=通配符 if ($admin =='*@some.text.here') { } $admin将是其中之一: xvilo@some.text.here 机器人!bot@some.text.here lakjsdflkjasdflkj@some.text.here 使用strstr()它会做你想做的事情,或者像stristr()指出的那样 或者您可以使用类似于这样的strpos $pos = strrpos($mystring, "@some
*
=通配符
if ($admin =='*@some.text.here') {
}
$admin
将是其中之一:
- xvilo@some.text.here
- 机器人!bot@some.text.here
- lakjsdflkjasdflkj@some.text.here
$pos = strrpos($mystring, "@some.text.here");
if ($pos === false) { // note: three equal signs
// not found...
} else {
//found
}
或者从最后(我想没有测试过)
您只需检查字符串是否以预期值结尾:
$suffix = '@some.text.here';
if (substr($admin, -strlen($suffix)) == $suffix) {
// Do something
}
检查是否在另一个字符串中找到一个字符串的最快方法是strpos(): 如果您需要确定@some.text.here出现在末尾,您可以使用substr\u compare()代替
这里有一个通配符函数供您使用。
由于您希望使用
*
,所以我只注释掉了
(单字符匹配)
这将允许您在整个过程中使用通配符:*xxx
-结束“xxx”xxx*
-启动“xxx”xx*zz
-以“xx”开头,以“zz”结尾<代码> *XX */COD> >中间有“XX”/P>
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()
。如果你不想使用正则表达式,这可能对你的[有限]用途很有帮助。它使用类似于shell的通配符匹配字符串,正如您所期望的那样
if (fnmatch('*@some.text.here', $admin)) {
}
不,但是您可能可以使用preg_match来实现您想要的功能。这与IRC有什么关系?如果没有输入,则
。==
是阻止您使用通配符的原因。寻找==
的替代方法。stristr是不区分大小写的版本。它假定@some.text是否在字符串末尾并不重要。这里的是否在字符串末尾。他没有在他的示例中说明他是否具体说明它在文本中的某个位置,而只是说明它在文本中。如果要从字符串末尾而不是从字符串末尾进行搜索,则始终可以使用strlen偏移量的strposanywherefoo@some.text.here在我看来像是一个电子邮件地址,在这种情况下@some.text.here可能位于字符串的末尾。由于我们可以对OP的意图做出许多假设,因此最好涵盖完整性的所有基础:)我不同意。意图似乎相当清楚。该示例不是$admin=='*@some.text。此处*'
结尾带有*
。如果从该示例开始,返回的位置为0=false-请参阅Dave的回答如果问题是0
隐式转换为false
,则显式转换为false
(使用
或直接转换)不会改变的。哇,绝对正确。不知道我是怎么想的!以前从没见过!美好的我会给你一个+1,因为我以前从来没有注意到这个函数非常有用。fnmatch失败,并警告文件名超过4096个字符。因为我匹配的是数据集而不是文件名,所以无法使用fnmatch
if (strpos($admin, '@some.test.here') !== false) { }
if (substr_compare($str, $test, strlen($str)-strlen($test), strlen($test)) === 0) {}
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)) {
}
if (fnmatch('*@some.text.here', $admin)) {
}