带有引号/撇号变量的WordPress查询


wordpress query with quote/apostrophe varrients

这是一个双重问题。我有一个 ajax 请求,它轮询重复的帖子标题,但它被不同的引号/撇号及其变体抛出,当我知道有重复时返回负数。

我有一篇题为"本的大鱼"的帖子,即带有撇号(’)

但是对以下内容进行查询总是返回负面结果:

Ben's Big Fish (')
Ben’s Big Fish (’)
Bens Big Fish (no apos)

但是,对 Big Fish 的查询会返回包含这些单词的所有变体帖子标题,包括带有引号和撇号的帖子标题。

以下是也导致问题的主要角色:

Apostrophe          '   '
Open single quote   ‘   ‘ 
Close single quote  ’   ’
--- 
Quotation mark      "   "
Open double quotes  “   “ 
Close double quotes ”   ”

由于用户经常从MS Word文档等中提取文本,因此这些字符出现了很多。

在 js 端,我通过此函数传递帖子标题来编码帖子标题,然后通过 json 将其发送到我的 ajax 处理程序:

function htmlEntities(str) {
    return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&apos;').replace(/‘/g, '&lsquo;').replace(/’/g, '&rsquo;').replace(/“/g, '&ldquo;').replace(/”/g, '&rdquo;');
} 

在我的 php ajax 钩子中,我按如下方式处理传入的 POST 查询:

global $wpdb;
// Grab details from inbound POST array & prepare for sql
$title = html_entity_decode($_POST['post_title']); //first un-encode
$post_id = $_POST['post_id'];
$sim_query = "SELECT ID FROM $wpdb->posts WHERE post_status = 'publish' AND post_title LIKE '%%%s%%' AND ID != '%d'";
$sim_results = $wpdb->get_results( $wpdb->prepare( $sim_query, $wpdb->esc_like($title), $post_id ) );
if ($sim_results)
{ // Send the results back as json }

所以我的问题是a) 如何让查询按预期返回明显的重复项b) 并且可能相关,有一种方法可以有效地搜索字符串,这些字符串无需多次查询即可查找撇号和引号字符的所有变体?

问题的症结实际上又回到了JS的原始编码上。让我们绊倒的关键人物之一:&apos;,实际上并没有被html_entity_decode解码,即使设置了ENT_QUOTES旗。相反,它期望&#039;.

所以最后我们的 js 看起来像:

function htmlEntities(str) {
    return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#039;').replace(/‘/g, '&lsquo;').replace(/’/g, '&rsquo;').replace(/“/g, '&ldquo;').replace(/”/g, '&rdquo;');
} 

我们用 PHP 解码:

 $title = html_entity_decode($_POST['post_title'], ENT_QUOTES,  'UTF-8' ); //first un-encode

同样重要的是要注意SQL会拒绝单引号和撇号。它要求通过像这样加倍来逃避它们:''.当我们使用它的SQL转义类时,WordPress会为我们处理转义$wpdb->prepare