Php search string (with wildcards)

后端 未结 5 960
自闭症患者
自闭症患者 2021-01-05 03:27

Is there a way to put a wildcard in a string? The reason why I am asking is because currently I have a function to search for a substring between two substrings (i.e grab th

5条回答
  •  旧巷少年郎
    2021-01-05 03:56

    I agree that regex are much more flexible than wildcards, but sometimes all you want is a simple way to define patterns. For people looking for a portable solution (not *NIX only) here is my implementation of the function:

    function wild_compare($wild, $string) {
        $wild_i = 0;
        $string_i = 0;
    
        $wild_len = strlen($wild);
        $string_len = strlen($string);
    
        while ($string_i < $string_len && $wild[$wild_i] != '*') {
            if (($wild[$wild_i] != $string[$string_i]) && ($wild[$wild_i] != '?')) {
                return 0;
            }
            $wild_i++;
            $string_i++;
        }
    
        $mp = 0;
        $cp = 0;
    
        while ($string_i < $string_len) {
            if ($wild[$wild_i] == '*') {
                if (++$wild_i == $wild_len) {
                    return 1;
                }
                $mp = $wild_i;
                $cp = $string_i + 1;
            }
            else
            if (($wild[$wild_i] == $string[$string_i]) || ($wild[$wild_i] == '?')) {
                $wild_i++;
                $string_i++;
            }
            else {
                $wild_i = $mp;
                $string_i = $cp++;
            }
        }
    
        while ($wild[$wild_i] == '*') {
            $wild_i++;
        }
    
        return $wild_i == $wild_len ? 1 : 0;
    }
    

    Naturally the PHP implementation is slower than fnmatch(), but it would work on any platform.

    It can be used like this:

    if (wild_compare('regex are * useful', 'regex are always useful') == 1) {
        echo "I'm glad we agree on this";
    }
    

提交回复
热议问题