Skip to content

Instantly share code, notes, and snippets.

@wingsline
Created January 3, 2013 05:54
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save wingsline/4441139 to your computer and use it in GitHub Desktop.
Save wingsline/4441139 to your computer and use it in GitHub Desktop.
Laravel: SQLite REGEXP
// create the function
DB::connection()->pdo->sqliteCreateFunction("REGEXP", "preg_match", 2);
// build a query
DB::table('tablename')->raw_where('REGEXP("#^[a-z]+$#iu", tablename.row)')->get();
@maxiskell
Copy link

Thanks for this great line!

I don't know for older versions, but as for L5, you should go this way:

// create the function
DB::connection()->getPdo()->sqliteCreateFunction("REGEXP", "preg_match", 2);

since DB wouldn't allow you to access 'pdo' as it's a private property now.

see http://laravel.com/docs/4.2/database#accessing-connections

@strebl
Copy link

strebl commented May 25, 2015

Thanks!

@arthurkirkosa
Copy link

If you're using both SQLITE and MySQL

DB::connection()->getPdo()->sqliteCreateFunction('REGEXP', function ($pattern, $value) {
                mb_regex_encoding('UTF-8');
                return (false !== mb_ereg("/$pattern/", $value)) ? 1 : 0;
            });

is a good alternative;

@RDelorier
Copy link

Thanks all for this thread 👏

@dododedodonl
Copy link

dododedodonl commented Jul 2, 2017

I had to remove the delimiter to make this work. I use this code in my AppServiceProvider.

if (DB::Connection() instanceof \Illuminate\Database\SQLiteConnection) {
    DB::connection()->getPdo()->sqliteCreateFunction('REGEXP', function ($pattern, $value) {
        mb_regex_encoding('UTF-8');
        return (false !== mb_ereg($pattern, $value)) ? 1 : 0;
    });
}

@GonzaloGPF
Copy link

Thanks! Works perfectly!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment