【问题标题】:Need help in replacing space with hyphen in URL需要帮助在 URL 中用连字符替换空格
【发布时间】:2015-12-15 12:16:09
【问题描述】:

我在这个网站上尝试了很多可用的选项,但无法解决我的问题。 我的代码:

<?php       
$district = $_GET['district'];
$state = $_GET['state'];        
$con = mysqli_connect('localhost','codeslib_service','service','codeslib_vdr123');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}    

// the query, limit the number of results to 5
$sql="SELECT * FROM pincodes WHERE districtName='$district' AND stateName='$state'";    
$result = mysqli_query($con,$sql);      
$row = $result->fetch_assoc();    
$district = $row['districtName'];   
$office = $row['officeName'];       
$state = $row['stateName'];
$pincode = $row['pinCode'];
?>

.htaccess:

RewriteRule ^([^/]*)/([^/]*)$ district.php?state=$1&amp;district=$2 [L]

现在,上面的代码正在生成像domainname.com/pincode/Delhi/Andhra Pradesh这样的URL

虽然我不想在 URL 中有空格,但想用连字符 (-) 替换空格。 尝试了很多东西但没有任何收获,请帮助我。

谢谢,

维卡斯

【问题讨论】:

    标签: php .htaccess url rewrite


    【解决方案1】:

    终于破解了,我用str_replace的方法如下:

    str_replace("-", "", $url);

    在谷歌和论坛上,我注意到第一个值是空格,然后是连字符,我必须将其反转以使用基于连字符的网址:)

    【讨论】:

      【解决方案2】:

      要用连字符替换所有空格,您可以在 .htaccess 顶部使用此规则:

      RewriteEngine On
      
      # redirect when only one space is left    
      RewriteRule "^(\S*)\s+(\S*)$" /$1-$2 [L,R=302]
      
      # otherwise rewrite by replacing each space by -
      RewriteRule "^(\S*)\s+(\S*\s+.*)$" $1-$2 [L]
      

      【讨论】:

      • 它在我的本地 apache 上运行良好。确保这些是第一条规则并打招呼以启用重写日志并将其发布在问题上。
      【解决方案3】:

      尝试在 htaccess 中的任何其他规则之前编写此代码

      RewriteEngine On
      RewriteRule ^/?/(.*)\ (.*)$ /$1-$2   [L,R=301]
      

      这会将 URL 中的空格替换为连字符 (-)

      【讨论】:

      • 我不明白这里的 ?tag。你的意思是?区还是?州?或者您能否在从我的代码中选择适当的标签后,向我提供这条规则添加确切的规则?
      【解决方案4】:
      # keep replacing space to hyphen until there is no space use internal rewrite
      RewriteRule ^([^\s%20]*)[\s%20]+(.*)$ $1-$2 [E=NOSPACE:1]
      
      # when there is no space make an external redirection
      RewriteCond %{ENV:NOSPACE} =1
      RewriteRule ^([^\s%20]+)$ $1 [R=301,L]
      

      这会将所有空格字符(\s%20)替换为连字符 -

      所以/tag/bob%20hope%20is%20funny 的URI 将变为/tag/bob-hope-is-funny 301

      【讨论】:

      • Shailesh 我已经尝试过了,但没有任何好处,问题一直存在。
      【解决方案5】:

      你试过 str_replace 吗?

      like str_replace(" ", "-", $url);

      【讨论】:

      • 是的 pali,我做了但没有收获。这对锚标签很有帮助,但对 $_GET 东西没有帮助
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-29
      • 1970-01-01
      • 2017-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多