Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

match string with asterisk

Tags:

regex

php

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.

like image 809
TDSii Avatar asked Sep 17 '26 06:09

TDSii


2 Answers

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);
}
like image 44
Czechnology Avatar answered Sep 18 '26 21:09

Czechnology