用PHP解码和编码?

时间:2017-11-11 07:22:01

标签: php mysql

我对如何在PHP中使用URL解码和编码感到有些困惑,我需要对此进行一些澄清。

基本上,我有一个MYSQL数据,其中包含单引号:

This is the third\'s title that goes here!!

'是单引号的HTML代码。

现在我在URL中使用它,如下所示:

title.php?t=This is the third's title that goes here!!

在我的PHP代码中,我尝试使用它:

$title = $_GET['t'];

$urlsafe_title = urlencode($title);
$url = $urlsafe_title;
$htmlsafe_url = htmlspecialchars($url, ENT_QUOTES | ENT_HTML5);


$title = utf8_decode(urldecode($htmlsafe_url));

但是当我尝试使用该变量$ title来搜索MYSQL数据库时,我根本得不到任何结果。但是当我从标题和MYSQL数据库中删除单引号时,一切正常。

有人可以就此问题提出建议吗?

提前致谢。

1 个答案:

答案 0 :(得分:1)

我认为你应该使用URL slugs,就像“Hello World”这样的输入可以作为“hello-world”发送。所以这是一个可以帮助你的功能:

function gen_slug($url)
{
    //prepare string with basic normalization
    $url = strtolower($url);
    $url = strip_tags($url);
    $url = stripslashes($url);
    $url = html_entity_decode($url);
    //Remove any quotes
    $url = str_replace('\"','',$url);
    //Replace non-alpha chars with '-'
    $match = '/[^a-z0-9]+/';
    $replace = '-';
    $url = preg_replace($match, $replace, $url);
    $url = trim($url, '-');
    return $url;
}

您必须在桌面上创建一个额外的列,例如title-slug或类似的内容,因此您可以将其用作参考。

所以在你的情况下,它可能是这样的:title.php?t=this-is-my-title

希望它对你有所帮助! :)