【问题标题】:Matching string with shell-style wildcards (e.g., *)使用 shell 风格的通配符匹配字符串(例如,*)
【发布时间】:2013-03-14 15:42:26
【问题描述】:

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

我的代码:

* = 通配符

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

}

$admin 将是其中之一:

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

【问题讨论】:

  • 不,但您可以使用 preg_match 来满足您的需求。
  • 这和IRC有什么关系?
  • if 没有进入它。 == 是阻止您使用通配符的原因。寻找== 的替代品。

标签: php string wildcard


【解决方案1】:

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

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

}

【讨论】:

  • 我会给你一个+1,因为我以前从未注意到这个功能非常有用。
  • fnmatch 失败,并显示有关文件名超过 4096 个字符的警告。因为我匹配的是数据集而不是文件名,所以我不能使用 fnmatch
【解决方案2】:

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

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

if (substr($admin, -strlen($suffix)) == $suffix) {
    // Do something
}

【讨论】:

    【解决方案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)) {
    
    }
    

    但我建议自己学习使用regular expressionspreg_match()

    【讨论】:

    • 哦哦!以前从未见过!不错!
    【解决方案4】:
    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
    }
    

    【讨论】:

    • stristr 是不区分大小写的版本
    • 这确实假设@some.text.here是否在字符串的末尾并不重要。
    • 他没有在他的例子中说明他是否具体说明它在文本中的某个位置,只是它在文本中。如果你想从字符串的末尾而不是任何地方搜索,你总是可以使用带有 strlen 偏移量的 strpos
    • foo@some.text.here 对我来说看起来像是一个电子邮件地址,在这种情况下,@some.text.here 可能意味着位于字符串的末尾。由于我们可以对 OP 意图做出许多假设,因此最好涵盖所有基础以确保完整性:)
    • 我不同意。意图似乎相当明确。这个例子不是$admin =='*@some.text.here*',最后是*
    【解决方案5】:

    检查一个字符串是否在另一个字符串中找到的最快方法是 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) {}
    

    【讨论】:

    • 如果以它开头,则返回的位置为 0 = false - 请参阅 Dave 的回答
    • 如果问题是0 被隐式转换为false显式 将其转换为false(使用!! 或直接转换)不是会改变这一点。
    • 哦,哇,完全正确。不知道我在想什么。
    猜你喜欢
    • 2015-07-29
    • 1970-01-01
    • 1970-01-01
    • 2011-09-04
    • 1970-01-01
    • 2017-10-28
    • 1970-01-01
    • 2018-01-01
    • 1970-01-01
    相关资源
    最近更新 更多