Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Analog of MySQL like function

Tags:

function

php

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

like image 279
DCrystal Avatar asked Apr 29 '10 17:04

DCrystal


People also ask

What does like do in MySQL?

The MySQL LIKE Operator The LIKE operator is used in a WHERE clause to search for a specified pattern in a column. There are two wildcards often used in conjunction with the LIKE operator: The percent sign (%) represents zero, one, or multiple characters. The underscore sign (_) represents one, single character.

Is like the same as MySQL?

As you put it, there is NO difference.

How do I match a string in MySQL?

STRCMP() function in MySQL is used to compare two strings. If both of the strings are same then it returns 0, if the first argument is smaller than the second according to the defined order it returns -1 and it returns 1 when the second one is smaller the first one.

How do I get the first letter of a string in MySQL?

To fetch the first alphabet from the strings, use LEFT(). This method allows you to return characters from the left of the string.


2 Answers

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.

like image 112
davidtbernal Avatar answered Oct 30 '22 02:10

davidtbernal


Take a look at the fnmatch function.

like image 31
Matěj G. Avatar answered Oct 30 '22 02:10

Matěj G.