wpdb::esc_like()publicWP 4.0.0

Prepares a string for use in the LIKE part of an SQL query. Processes special characters % and _.

Example:

$find = 'only 43% of planets';
$like = '%' . $wpdb->esc_like( $find ) . '%';
$sql  = $wpdb->prepare(
	"SELECT * FROM $wpdb->posts WHERE post_content LIKE %s",
	$like
);

Example of a chain of calls:

$sql = esc_sql( $wpdb->esc_like( $input ) );

Use before wpdb::prepare() or esc_sql().

Does not protect against SQL injections. For such protection, the result needs to be additionally processed by one of the functions: wpdb::prepare() or esc_sql().

Used instead of the deprecated function like_escape( $string ) since WP 4.0.

Method of the class: wpdb{}

1 time — 0.00001 sec (speed of light) | 50000 times — 0.01 sec (speed of light) | PHP 7.4.8, WP 5.6.2

No Hooks.

Returns

String. Text for the LIKE part of the query. The result is not sanitized for the SQL query, so use wpdb::prepare() or wpdb::_real_escape() to add the result to the query.

Usage

global $wpdb;
$wpdb->esc_like( $text );
$text(string) (required)
Unprocessed text, in which special characters need to be escaped for the LIKE string. The string should not have additional or removed slashes.

Examples

0

#1 Example of preparing a string for a LIKE query

$find = 'only 43% of planets';
$sql  = $wpdb->prepare( 
	"SELECT * FROM $wpdb->posts WHERE post_content LIKE %s", 
	'%' . $wpdb->esc_like( $find ) . '%' 
);

echo $sql; // SELECT * FROM wp_posts WHERE post_content LIKE '{d710cab}only 43\{d710cab} of planets{d710cab}'
0

#2 Example with esc_sql()

$esc_like = $wpdb->esc_like( 'only 43% of planets' );
echo $esc_like;                                        // only 43\% of planets
echo esc_sql( $esc_like );                             // only 43\{f5fa52} of planets
0

#3 Another example of preparing a string for a LIKE query

global $wpdb;
$link = $wpdb->esc_like( $link ); // prepare a string for the LIKE argument
$link = esc_sql( $link ); // clear the variable
$link = '%' . $link . '%'; // create a full LIKE search variable

// find comments in the text or link of the author, there is a specified link
$spammy = $wpdb->query("SELECT comment_approved FROM $wpdb->comments
	WHERE (comment_content LIKE '$link' OR comment_author_url LIKE '$link')
		AND comment_approved = 'spam'
	LIMIT 1;"
);
0

#4 A short recording with prepare()

global $wpdb;

$link = '%' . $wpdb->esc_like( $link ) . '%';

$comment = $wpdb->get_row( $wpdb->prepare(
	"SELECT * FROM $wpdb->comments WHERE comment_author_url LIKE %s LIMIT 1", $link
) );

Changelog

Since 4.0.0 Introduced.

wpdb::esc_like() code WP 6.9.1

public function esc_like( $text ) {
	return addcslashes( $text, '_%\\' );
}