PHP使用变量时的连字符问题
我的网站是一个搜索引擎。
在我的 .htaccess 文件中,我有:
RewriteRule ^news/(.*)\.html$ /results/news.php?name=$1
我的链接结构是使用连字符的 /news/what-is-up.html
。
当我搜索 /results/news.php?name=hello world 时,我得到的结果与使用 /news/hello-world.html 时得到的结果
不同正在使用连字符而不是空格搜索 hello-world
,我可以使用 +
符号轻松解决它,但我想使用连字符。有谁知道该怎么做?
这是我用来将名称变量转换为 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();
}
谢谢
My website is a search engine.
In my .htaccess file I have:
RewriteRule ^news/(.*)\.html$ /results/news.php?name=$1
And my link structure is /news/what-is-up.html
using hyphens.
When I search for /results/news.php?name=hello world I get different results than when I use /news/hello-world.html
It seems that the search is searching for hello-world
using hypens instead of spaces, I could easily solve it using a +
sign but I want to use hyphens. Does anyone know how to do it?
This is the code I use for converting the name variable into URL friendly:
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;
}
and my search engine uses http location like this:
if ($q != '') {
header( 'Location: http://'.$_SERVER['SERVER_NAME'].'/news/'.toAscii($q).'.html' );
die();
}
else
{
header('Location:http://'.$_SERVER['SERVER_NAME'].'/news/');
die();
}
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我理解您正确使用 str_replace 将连字符替换为空格,然后再将其提交到您的搜索。
If I have understood you correctly use str_replace to replace a hyphen with a space before submitting it to your search.
由于它正在被重写,因此您需要在您的末端处理分词。
你能做的就是拥有
如果 $_GET['rewrite'] 存在,则执行 str_replace(" -", " ", $传入)
You need to handle word splitting on your end since it's being rewritten.
What you can do is have
and if $_GET['rewrite'] is present, you do str_replace("-", " ", $incoming)