Skip to content

Instantly share code, notes, and snippets.

@matt-allan
Created August 24, 2016 17:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matt-allan/10d81eb28d2402afef0800bd4f158c4e to your computer and use it in GitHub Desktop.
Save matt-allan/10d81eb28d2402afef0800bd4f158c4e to your computer and use it in GitHub Desktop.
<?php
function likeToRegex($like)
{
// replace all % characters that are not escaped with .*
$regex = preg_replace('/(?<!\\\)%/', '.*', $like);
// replace all escaped % characters with %
$regex = str_replace('\%', '%', $regex);
// replace all unescaped _ characters with .{1}
$regex = preg_replace('/(?<!\\\)_/', '.{1}', $regex);
// replace all escaped _ characters with _
$regex = str_replace('\_', '_', $regex);
// add delimiters
return '/' . str_replace('/', '\\/', $regex) . '/';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment