Nick Nick - 7 months ago 26
SQL Question

Regular Expression inside a MySQL Like value

Reg ex again.

Trying to run a like SQL query:

mysql_query("SELECT * From tablename WHERE somthing LIKE '%id|length:3:\"{$id}\"%'");


problem is the length value will be unknown, only the ID.

Of course, I could use strlen($id) and do this:

$len = intval(strlen($id));
mysql_query("SELECT * From tablename WHERE somthing LIKE '%id|length:{$len}:\"{$id}\"%'");


But I dont really care to check the len value, there's gotta be a bit of Reg ex to match anything where the length will be and sort this without having to calc the length before.

mysql_query("SELECT * From tablename WHERE somthing LIKE '%id|length:^*:\"{$id}\"%'");


ideas?

Answer

@Naddiseo's link is a good one, I recommend you use REGEXP. What do you mean by 'No exact example matching'?

Try something like (I added in the newlines for readability):

mysql_query("SELECT * From tablename 
             WHERE somthing 
             REGEXP '^.*id\\\|length:[0-9]+:\"{$id}\".*$'");

The relevant regex without worrying about escaping for MYSQL/php strings is

^.*id\|length:[0-9]+:"abc".*$

(assuming abc is a particular ${id}).

It says, "look for anything followed by the literal string id|length: (I've escaped it as | has a special meaning in regex and you want literal |), followed by numbers ([0-9]+) being the length of the id, followed by :"{$id}" and anything else (where {$id} has been substituted in).

Now, if you read the MySQL regexp page that @Naddiseo quoted, you'd see that any backslashes need to be further escaped as MySQL parses backslashes as special characters.

So, if you were to enter this query into a MySQL command line (let's assume {$id} is abc for now), you'd have to type:

SELECT * From tablename 
  WHERE somthing 
  REGEXP '^.*id\\|length:[0-9]+:"abc".*$'

Now, since you are calling this from PHP inside double quotes, you need to escape your backslashes again to make sure the right number get through to MySQL, as well as backslashing your double quotes to escape them. Hence the three backslashes in the mysql_query above before the |.