php 字符串匹配通配符 *?

编程入门 行业动态 更新时间:2024-10-25 13:25:50
本文介绍了php 字符串匹配通配符 *?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想提供将字符串与通配符 * 匹配的可能性.

I want to give the possibility to match string with wildcard *.

示例

$mystring = 'dir/folder1/file'; $pattern = 'dir/*/file'; stringMatchWithWildcard($mystring,$pattern); //> Returns true

示例 2:

$mystring = 'string bl#abla;y'; $pattern = 'string*y'; stringMatchWithWildcard($mystring,$pattern); //> Returns true

我的想法是这样的:

function stringMatch($source,$pattern) { $pattern = preg_quote($pattern,'/'); $pattern = str_replace( '\*' , '.*?', $pattern); //> This is the important replace return (bool)preg_match( '/^' . $pattern . '$/i' , $source ); }

基本上将*替换为.*?(考虑在*nix环境中*匹配empty 字符串) ©vbence

Basically replacing * to .*? (considering in *nix environment * matches empty string) ©vbence

任何改进/建议?

//添加了 return (bool) 因为 preg_match 返回 int

// Added return (bool) because preg_match returns int

推荐答案

这里不需要 preg_match.PHP 有一个通配符比较功能,专门针对这种情况:

There is no need for preg_match here. PHP has a wildcard comparison function, specifically made for such cases:

fnmatch()

而且 fnmatch('dir/*/file', 'dir/folder1/file') 可能已经对你有用了.但要注意 * 通配符同样会添加更多斜线,就像 preg_match 一样.

And fnmatch('dir/*/file', 'dir/folder1/file') would likely already work for you. But beware that the * wildcard would likewise add further slashes, like preg_match would.

更多推荐

php 字符串匹配通配符 *?

本文发布于:2023-10-24 14:54:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524233.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:通配符   字符串   php

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!