匹配带星号的字符串
我想通过星号将字符串与另一个字符串进行匹配。匹配带星号的字符串
例子:我有
$var = "*world*";
我想打一个函数,要么返回true或false,以配合我的字符串。 不区分大小写
example:
match_string("*world*","hello world") // returns true
match_string("world*","hello world") // returns false
match_string("*world","hello world") // returns true
match_string("world*","hello world") // returns false
match_string("*ello*w*","hello world") // returns true
match_string("*w*o*r*l*d*","hello world") // returns true
的*只会在范围内匹配任何字符。我尝试使用preg_match几个小时没有运气。
function match_string($pattern, $str)
{
$pattern = preg_replace('/([^*])/e', 'preg_quote("$1", "/")', $pattern);
$pattern = str_replace('*', '.*', $pattern);
return (bool) preg_match('/^' . $pattern . '$/i', $str);
}
而且上面运行它在你的测试用例:
bool(true)
bool(false)
bool(true)
bool(false)
bool(true)
bool(true)
'preg_quote()'应该总是包含第二个参数,分隔符。在这种情况下,它应该是“/”。如果你不包含它,match_string(“hello/*”,“hello world”)会抛出一个错误。 – mcrumley 2011-04-11 13:54:28
试试这样说:
function match_string($match, $string) {
return preg_match("/$match/i", $string);
}
注意的preg_match实际上返回匹配的数目,但它比较真/假作品(0 =假,> 0 = TRUE)。请注意模式末尾的i
标志使匹配不区分大小写。
这会为你的下面的示例工作:
example:
match_string("world","hello world") // returns true
match_string(" world","hello world") // returns true
match_string("world ","hello world") // returns false
match_string("ello w","hello world") // returns true
match_string("world","hello world") // returns true
function match_string($patt, $haystack) {
$regex = '|^'. str_replace('\*', '.*', preg_quote($patt)) .'$|is';
return preg_match($regex, $haystack);
}
或使用'preg_quote':http://php.net/manual/en/function.preg-quote.php – 2011-04-11 13:44:59
感谢您的建议,我已经包括它。 – Czechnology 2011-04-11 13:48:09
您可以使用下面的代码来生成适当的正则表达式。否更换回调,没有自行车码
$var = "*world*";
$regex = preg_quote($var, '/'); // escape initial string
$regex = str_replace(preg_quote('*'), '.*?', $regex); // replace escaped asterisk to .*?
$regex = "/^$regex$/i"; // you have case insensitive regexp
没有必要preg_match
或str_replace
这里。 PHP有一个通配符比较功能,专门针对这种情况提出:
你的测试工作像预期与:
fnmatch("*world*","hello world") // returns true
fnmatch("world*","hello world") // returns false
fnmatch("*world","hello world") // returns true
fnmatch("world*","hello world") // returns false
fnmatch("*ello*w*","hello world") // returns true
fnmatch("*w*o*r*l*d*","hello world") // returns true
请注意,'fnmatch'使用适合当前操作系统shell的通配符,这可能不是您想要的。这意味着如果没有关于它将运行的操作系统的一些假设,代码是不可移植的。 – Jason 2016-04-04 22:38:33
什么是你最后一次尝试? – 2011-04-11 13:35:16
我最后一次尝试是用*(*)替换*以使用preg_match,但不知道我犯了什么错误。 – TDSii 2011-04-11 13:43:16
你从哪里得到字符串?为什么不使用“正常”正则表达式? – 2011-04-11 13:43:33