Php search string (with wildcards)

后端 未结 5 1013
自闭症患者
自闭症患者 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 04:00

    wildcard pattern could be converted to regex pattern like this

    function wildcard_match($pattern, $subject) {
      $pattern = strtr($pattern, array(
        '*' => '.*?', // 0 or more (lazy) - asterisk (*)
        '?' => '.', // 1 character - question mark (?)
      ));
      return preg_match("/$pattern/", $subject);
    }
    

    if string contents special characters, e.g. \.+*?^$|{}/'#, they should be \-escaped

    don't tested:

    function wildcard_match($pattern, $subject) {
      // quotemeta function has most similar behavior,
      // it escapes \.+*?^$[](), but doesn't escape |{}/'#
      // we don't include * and ?
      $special_chars = "\.+^$[]()|{}/'#";
      $special_chars = str_split($special_chars);
      $escape = array();
      foreach ($special_chars as $char) $escape[$char] = "\\$char";
      $pattern = strtr($pattern, $escape);
      $pattern = strtr($pattern, array(
        '*' => '.*?', // 0 or more (lazy) - asterisk (*)
        '?' => '.', // 1 character - question mark (?)
      ));
      return preg_match("/$pattern/", $subject);
    }
    

提交回复
热议问题