PHP 搜索字符串(带通配符)

发布于 2024-08-22 04:11:27 字数 520 浏览 6 评论 0原文

有没有办法在字符串中添加通配符?我之所以问这个问题,是因为目前我有一个函数可以搜索两个子字符串之间的子字符串(即抓取“我的狗有跳蚤”这句话中“我的”和“有跳蚤”之间的内容,从而得到“狗” )。

function get_string_between($string, $start, $end){ 
    $string = " ".$string; 
    $ini = strpos($string,$start); 
    if ($ini == 0) return ""; 
    $ini += strlen($start); 
    $len = strpos($string,$end,$ini) - $ini; 
    return substr($string,$ini,$len); 
} 

我想做的是让它在字符串中使用通配符进行搜索。假设我在“我的狗有跳蚤”这句话中在“%WILDCARD%”和“有跳蚤”之间搜索 - 它仍然会输出“狗”。

我不知道我是否解释得太好,但希望有人能理解我:P。非常感谢您的阅读!

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 the contents between "my" and "has fleas" in the sentence "my dog has fleas", resulting in "dog").

function get_string_between($string, $start, $end){ 
    $string = " ".$string; 
    $ini = strpos($string,$start); 
    if ($ini == 0) return ""; 
    $ini += strlen($start); 
    $len = strpos($string,$end,$ini) - $ini; 
    return substr($string,$ini,$len); 
} 

What I want to do is have it search with a wildcard in the string. So say I search between "%WILDCARD%" and "has fleas" in the sentence "My dog has fleas" - it would still output "dog".

I don't know if I explained it too well but hopefully someone will understand me :P. Thank you very much for reading!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

夕嗳→ 2024-08-29 04:11:27

这是正则表达式真正有用的少数情况之一。 :)

if (preg_match('/my (\w+) has/', $str, $matches)) {
    echo $matches[1];
}

请参阅 preg_match 的文档。

This is one of the few cases where regular expressions are actually helpful. :)

if (preg_match('/my (\w+) has/', $str, $matches)) {
    echo $matches[1];
}

See the documentation for preg_match.

勿忘心安 2024-08-29 04:11:27

通配符模式可以转换为正则表达式模式,如下所示

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

如果字符串包含特殊字符,例如 \.+*?^$|{}/'#,则

,它们应该是 \-转义的,不进行测试:

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);
}

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);
}
残龙傲雪 2024-08-29 04:11:27

使用正则表达式。

$string = "My dog has fleas";
if (preg_match("/\S+ (\S+) has fleas/", $string, $matches))
  echo ($matches[1]);
else
  echo ("Not found");

\S 表示任何非空格字符,+ 表示前面的一个或多个字符,因此 \S+ 表示匹配一个或多个非空格字符。 (…) 表示捕获子匹配的内容并放入 $matches 数组中。

Use a regex.

$string = "My dog has fleas";
if (preg_match("/\S+ (\S+) has fleas/", $string, $matches))
  echo ($matches[1]);
else
  echo ("Not found");

\S means any non-space character, + means one or more of the previous thing, so \S+ means match one or more non-space characters. (…) means capture the content of the submatch and put into the $matches array.

灰色世界里的红玫瑰 2024-08-29 04:11:27

我同意正则表达式比通配符灵活得多,但有时您想要的只是一种定义模式的简单方法。对于寻找便携式解决方案(不仅仅是 *NIX)的人来说,这是我的函数实现:

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;
}

当然,PHP 实现比 fnmatch() 慢,但它可以在任何平台上工作。

它可以这样使用:

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

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";
}
淡笑忘祈一世凡恋 2024-08-29 04:11:27

如果您坚持使用通配符(是的,PREG 更好),您可以使用该函数
fnmatch

前任:

if (fnmatch('my * has', $str)) { }

If you insist to use a wildcard (and yes, PREG is much better) you can use the function
fnmatch.

ex:

if (fnmatch('my * has', $str)) { }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文