tags:

views:

78

answers:

4

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

A: 

In case the strings you want to match are actually files in a directory, check out the glob function: http://php.net/manual/en/function.glob.php

Vebjorn Ljosa
That's not even close to the same thing.
notJim
glob() is fine, but it can't be use with usual strings, i suppose...
DCrystal
Thanks for pointing out that `glob()` is specific to files in a directory, not arbitrary strings. I have edited the answer to clarify.
Vebjorn Ljosa
+3  A: 

all of those scenarios can be accomplished with strpos

Rich
Thanks, i just don't wanna make another wheel:)
DCrystal
how is substr good for this?! must be some new use for it?
OIS
lol...I meant strpos
Rich
+5  A: 

Take a look at the fnmatch function.

Matěj Grabovský
Before 5.3, this only works on Linux (probably not a problem, just FYI.)
notJim
@notJim, thanks for the rectification, though it's not really a problem :)
DCrystal
+3  A: 

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.

notJim