Php – Analog of MySQL like function

functionphp

Suppose it's a nub question, but is there an analog of MySQL's LIKE function in PHP?

So, e.g.

like('goo*','google.com');//is true
like('*gl*','google.com');//true
like('google.com','google.com')//also true

I know regex rullez, but don't know any solution to reach this

Best Solution

For the first, use strpos:

like('goo*','google.com');      -->  strpos('goo','google.com') === 0

The next one, you can use strpos:

like('*gl*','google.com');      -->  strpos('gl', 'google.com') !== false;

The next you can just use equals:

like('google.com','google.com') -->  'google.com' == 'google.com'

Of course, you can use regex for all of them:

like('goo*','google.com');      -->  preg_match('#^goo.*$#','google.com') 
like('*gl*','google.com');      -->  preg_match('#^.*gl.*$#', 'google.com');
like('google.com','google.com') -->  preg_match('#^google\.com$#', 'google.com')

Edit: to convert your patterns to regex, place a ^ at the beginning, and a $ at the end, then replace * with .* and escape .s.