like_escape()
Use instead of wpdb::esc_like(). Prepares a string for use in a SQL query LIKE expression. Since version 4.0, it is considered deprecated!
Everything described here is fully applicable to wpdb::esc_like(). Roughly speaking, you just need to replace all like_escape() with $wpdb->esc_like().
The function does not protect the string from SQL injections, and the string must still be separately processed by the functions $wpdb->prepare() or esc_sql().
The function escapes the percent sign (%) and underscore (_), as they have special meaning in the LIKE argument of the query.
No Hooks.
Returns
String. Prepared for use in the LIKE value in a SQL query.
Usage
like_escape( $text );
- $text(string) (required)
- The part of the SQL query that will be used for searching with the LIKE command.
Examples
#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.'; #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
- See: wpdb::esc_like()
Changelog
| Since 2.5.0 | Introduced. |
| Deprecated since 4.0.0 | Use wpdb::esc_like() |
like_escape() like escape code WP 6.9.1
function like_escape($text) {
_deprecated_function( __FUNCTION__, '4.0.0', 'wpdb::esc_like()' );
return str_replace( array( "%", "_" ), array( "\\%", "\\_" ), $text );
}