like_escape()WP 2.5.0

Deprecated from version 4.0.0. It is no longer supported and can be removed in future releases. Use wpdb::esc_like() instead.

Formerly used to escape strings before searching the DB. It was poorly documented and never worked as described.

No Hooks.

Return

String. text, safe for inclusion in LIKE query.

Usage

like_escape( $text );
$text(string) (required)
The text to be escaped.

Examples

0

#1 Example with $wpdb->esc_like, which is considered correct since WordPress 4.0

This example shows how to compare a given commenter URL with URLs of commenters that are flagged as spam:

// Process the transmitted URL
$url = parse_url( $suspicious_link );

// Remove "http://" and URL parameters
if ( isset( $url['path'] ) ) {
	$link = $url['host'] . $url['path'];
}
else {
	$link = $url['host'];
}

// prepare for use in the LIKE argument
$link = $wpdb->esc_like( $link );

// add percent signs to the ends of the search argument
$link = '%' . $link . '%';

// Create a query string with % placeholders to replace those in $wpdb->prepare()
$sql =  "
	SELECT COUNT(*)
	FROM $wpdb->comments
	WHERE (comment_content LIKE %s OR comment_author_url LIKE %s)
		AND comment_approved = 'spam'
	";

// Prepare and clear the string with $wpdb->prepare()
$sql = $wpdb->prepare( $sql, $link, $link );

//Send request
$matching_comments = $wpdb->get_var( $sql );

echo $matching_comments . ' spam comments found with this link.';
0

#2 Demo of LIKE argument processing in SQL queries

This example shows in detail how to handle the LIKE argument of an SQL query.

The code below shows how to compare the suspicious link we have with links in spam comments to see if the link is spam.

// prepare for use in the LIKE argument
$link = like_escape( $link );

// string cleaning is also needed
$link = esc_sql( $link );

// add percent signs to the ends of the search argument
$link = '%' . $link . '%';

// search for spam comments with a similar link in the comment text or the author's 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;"
);
// If $spammy == 1 then the suspicious link is found in spam comments

Notes

Changelog

Since 2.5.0 Introduced.
Deprecated since 4.0.0 Use wpdb::esc_like()

like_escape() code WP 6.5.3

function like_escape($text) {
	_deprecated_function( __FUNCTION__, '4.0.0', 'wpdb::esc_like()' );
	return str_replace( array( "%", "_" ), array( "\\%", "\\_" ), $text );
}