I want to match a string with another via asterisk.
example: i have
$var = "*world*";
i want to make a function that will either return true or false to match my string. case insensitive
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
the * will just match any character in range. i tried using preg_match for hours with no luck.
function match_string($pattern, $str)
{
$pattern = preg_replace('/([^*])/e', 'preg_quote("$1", "/")', $pattern);
$pattern = str_replace('*', '.*', $pattern);
return (bool) preg_match('/^' . $pattern . '$/i', $str);
}
And running it on your test cases above:
bool(true)
bool(false)
bool(true)
bool(false)
bool(true)
bool(true)
function match_string($patt, $haystack) {
$regex = '|^'. str_replace('\*', '.*', preg_quote($patt)) .'$|is';
return preg_match($regex, $haystack);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With