Skip to content

Commit

Permalink
First draft of adding regexp_replace function to SQLite
Browse files Browse the repository at this point in the history
  • Loading branch information
Zodiac1978 committed Jan 23, 2024
1 parent 8a4efbe commit 421e08d
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions wp-includes/sqlite/class-wp-sqlite-pdo-user-defined-functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ public function __construct( $pdo ) {
'isnull' => 'isnull',
'if' => '_if',
'regexp' => 'regexp',
'regexp_replace' => 'regexp_replace',
'field' => 'field',
'log' => 'log',
'least' => 'least',
Expand Down Expand Up @@ -492,6 +493,43 @@ public function regexp( $pattern, $field ) {
return preg_match( $pattern, $field );
}

/**
* Method to emulate MySQL REGEXP_REPLACE() function.
*
* @param string|array $pattern Regular expression to search for (or array of strings).
* @param string|array $replacement The string or an array with strings to replace.
* @param string|array $field Haystack.
*
* @return Array if the field parameter is an array, or a string otherwise.
*/
public function regexp_replace( $pattern, $replacement, $field ) {
/*
* If the original query says REGEXP BINARY
* the comparison is byte-by-byte and letter casing now
* matters since lower- and upper-case letters have different
* byte codes.
*
* The REGEXP function can't be easily made to accept two
* parameters, so we'll have to use a hack to get around this.
*
* If the first character of the pattern is a null byte, we'll
* remove it and make the comparison case-sensitive. This should
* be reasonably safe since PHP does not allow null bytes in
* regular expressions anyway.
*/
if ( "\x00" === $pattern[0] ) {

This comment has been minimized.

Copy link
@adamziel

adamziel Jun 13, 2024

Let's check if $pattern is a non-empty string. That may also be applicable to the other regexp function.

This comment has been minimized.

Copy link
@Zodiac1978

Zodiac1978 Jun 13, 2024

Author Owner

If expr, pat, or repl is NULL, the return value is NULL.

MySQL is returning NULL in this case.
See: https://dev.mysql.com/doc/refman/8.4/en/regexp.html#function_regexp-replace

$pattern = substr( $pattern, 1 );
$flags = '';
} else {
// Otherwise, the search is case-insensitive.
$flags = 'i';
}
$pattern = str_replace( '/', '\/', $pattern );
$pattern = '/' . $pattern . '/' . $flags;

return preg_replace( $pattern, $replacement, $field );
}

/**
* Method to emulate MySQL FIELD() function.
*
Expand Down

0 comments on commit 421e08d

Please sign in to comment.