【问题标题】:PHP hyphens problem when using a variable使用变量时的PHP连字符问题
【发布时间】:2010-12-22 15:19:08
【问题描述】:

我的网站是一个搜索引擎。

在我的 .htaccess 文件中:

RewriteRule ^news/(.*)\.html$ /results/news.php?name=$1

我的链接结构是/news/what-is-up.html,使用连字符。

当我搜索 /results/news.php?name=hello world 时,我得到的结果与我使用 /news/hello-world.html 时不同。 p>

似乎搜索是使用连字符而不是空格来搜索hello-world,我可以使用+ 符号轻松解决它,但我想使用连字符。有人知道怎么做吗?

这是我用于将 name 变量转换为 URL 友好的代码:

function toAscii($str, $replace=array(), $delimiter='-') {
if( !empty($replace) ) {
    $str = str_replace((array)$replace, ' ', $str);
}

$clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
$clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
$clean = strtolower(trim($clean, '-'));
$clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);

return $clean;
}

我的搜索引擎使用这样的 http 位置:

if ($q != '') {
   header( 'Location: http://'.$_SERVER['SERVER_NAME'].'/news/'.toAscii($q).'.html' );
   die();
}
else
{
    header('Location:http://'.$_SERVER['SERVER_NAME'].'/news/');
    die();
}

谢谢

【问题讨论】:

  • 替换连字符的代码块在哪里?我认为这与您的重写规则无关。 /results/news.php?name=hello-world 应该产生与 /news/hello-world.html 相同的结果
  • 关键字是 urldecode() 但仅适用于“+”号。
  • 如果有人实际上在寻找 hello-world 而不是 hello world 怎么办?
  • 我开始认为问题是在搜索中使用重定向...但我不知道如何以不同的方式进行:)
  • @Peibol:不,问题在于做这种不必要的“URL 友好”的事情。它掺假了用户输入,因此结果可能不是用户想要的。

标签: php apache url .htaccess mod-rewrite


【解决方案1】:

如果我理解您在提交搜索之前正确使用 str_replace 将连字符替换为空格。

$search_term = str_replace("-", " ", $incoming);

【讨论】:

  • 这暂时解决了这个问题,但我现在似乎有另一个问题,如上述评论中所述。谢谢。
  • 我认为问题可能是通过 get 字符串传入的 var 将被 urlencoded,因此 hello world 将显示为 hello%20world,因此您首先必须对 var 进行 urldecode() 以防万一用户有输入空格。
【解决方案2】:

你需要自己处理分词,因为它正在被重写。

你能做的就是拥有

RewriteRule ^news/(.*).html$ /results/news.php?name=$1&rewrite=true

如果 $_GET['rewrite'] 存在,则执行 str_replace("-", " ", $incoming)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-10
    • 1970-01-01
    • 1970-01-01
    • 2013-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多