【问题标题】:Comparing Path String With Wildcard in PHP在 PHP 中比较路径字符串与通配符
【发布时间】:2012-07-21 15:58:20
【问题描述】:

如何比较这个字符串:

commodity/search/oil/branch/index

有了这个:

commodity/search/*/branch/index

虽然“油”被替换为其他词,但它应该返回 true。

【问题讨论】:

标签: php string compare


【解决方案1】:
$match = preg_match("/commodity\/search\/(.*)\/branch\/index/", "commodity/search/someotherword/branch/index");

如果找到匹配项,$match 将为真(或某个值评估为真,如 1)。

注意:以上将匹配任何额外的路径,例如commodity/search/some/other/word/branch/index

如果您只想匹配一个单词,而不是类似于路径结构的东西,那么您可以尝试这样的操作:

$match = preg_match("/commodity\/search\/[A-Za-z0-9_-]+\/branch\/index/", "commodity/search/some-OTHER_word/branch/index");

这只会匹配大小写的 a-z 字符、数字、连字符和下划线。根据需要进行调整。

【讨论】:

  • 也可以是'/commodity\/search\/[^\/:\\;]+\/branch\/index/"
  • 如何动态构建模式?
【解决方案2】:

PHP 有一个内置函数,称为fnmatch()

它提供了基本通配符的用法。

<?php

if (fnmatch('commodity/search/*/branch/index', 'commodity/search/oil/branch/index')) {
    echo "It matches!";
}

但不支持非 POSIX 兼容的系统(请参阅 PHP 手册)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-10
    • 2014-12-02
    • 2013-11-22
    • 2016-05-09
    • 1970-01-01
    相关资源
    最近更新 更多