我想通过星号将字符串与另一个字符串匹配。
示例:我有
$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几个小时没有运气。
答案 0 :(得分:4)
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)
答案 1 :(得分:2)
function match_string($patt, $haystack) {
$regex = '|^'. str_replace('\*', '.*', preg_quote($patt)) .'$|is';
return preg_match($regex, $haystack);
}
答案 2 :(得分:1)
试试这样:
function match_string($match, $string) {
return preg_match("/$match/i", $string);
}
请注意,preg_match实际上返回匹配数,但将其与true / false进行比较(0 = false,> 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
答案 3 :(得分:1)
您可以使用以下代码生成正确的正则表达式。没有替换回调,没有自行车代码
$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
答案 4 :(得分:1)
对于PHP 7(太PHP 5.6)
<?php
function match_string($pattern, $str)
{
$pattern = preg_replace_callback('/([^*])/', 'testPRC', $pattern);
$pattern = str_replace('*', '.*', $pattern);
return (bool) preg_match('/^' . $pattern . '$/i', $str);
}
function testPRC($m) {
return preg_quote($m[1],"/");
}
echo match_string("*world*","hello world"); // returns true
echo match_string("world*","hello world"); // returns false
echo match_string("*world","hello world"); // returns true
echo match_string("world*","hello world"); // returns false
echo match_string("*ello*w*","hello world"); // returns true
echo match_string("*w*o*r*l*d*","hello world"); // returns true
答案 5 :(得分:-1)
此处无需preg_match
或str_replace
。 PHP具有通配符比较功能,专门用于此类情况:
您的测试与预期fnmatch()
的工作方式相同:
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