繁体   English   中英

在URL php中用连字符替换空格和正斜杠

[英]Replace space and forward slash with hyphen in URL php

我想用连字符例如www.example.com/car/ 宝马/保时捷替换URL的空间和斜杠,其中宝马/保时捷是一个value..but似乎工作正斜杠不。

这就是我所拥有的空间:

$name = str_replace("-", " ", $request[2]);
$id = $category->find_id_by_name($name);

但是当我为正斜杠添加它时,它不起作用..虽然它仍适用于空间:

$name = str_replace(array("-","//"), " ", $request[2]);
$id = $category->find_id_by_name($name);

我该如何改变它?

编辑

所以我将代码更改为以下内容:

$char = " ";
$name = str_replace("-", $char, $request[2]);
$id = $category->find_id_by_name($name);

然后我将$char放在一个像$char = array(" ", "/");这样的$char = array(" ", "/"); 这给了我以下内容: Notice: Array to string conversion然后我尝试通过它们的索引获取它们,如下所示:

$name = str_replace("-", $char[0], $request[2]);<-- works for forward slash but not space

$name = str_replace("-", $char[1], $request[2]);<-- works for space but not forward slash 

我似乎无法让他们一起工作:(


[新编辑]

class CarController extends Zend_Controller_Action {

    public function indexAction() {

        $category = new Application_Model_CarMapper();
        $gcat = $this->getRequest()->getPathInfo();

        $request = explode("/", $gcat);
        //die(print_r($request));

        if (isset($request[2])) {
            $char = array("/"," ");
            $name = str_replace("-", $char, $request[2]);//<-- "-" and "$char swapped over"
            $id = $category->find_id_by_name($name);
            $this->view->title = $id['name'];
            //die(print_r($request));

            $this->view->selectsub = $category->get_sub_cat_select($id['id']);


        }
    }

}

VAR DUMP

array (size=4)
  0 => string '' (length=0)
  1 => string 'car' (length=3)
  2 => string 'bmw-porsche' (length=11)
  3 => string '' (length=0)

您可以使用urlencode()

$myUri = "Bmw/Porsche"; // Or set it accordingly by retreiving from your database
$uriCompatible = urlencode($myUri); // Results in "Bmw%2FPorsche"
$myUrl = "www.example.com/car/" . $uriCompatible;

您可以使用urldecode()来检索它:

echo $request[2]; // Results in "Bmw%2FPorsche"
$myUri = urldecode($request[2]); // Results in "Bmw/Porsche";

I am trying to replace a space and forward slash in a url with a hyphen

那你应该有

$name = str_replace(" ", "-", $request[2]);

$name = str_replace(array(" ","/"), "-", $request[2]);

使用单引号而不是双引号它将起作用。 像这样:

$name = str_replace(array('-','/'), " ", $request[2]);
$id = $category->find_id_by_name($name);

你不必逃避“/”。 需要在这里逃避反击,但不要向前冲去。

$name = str_replace(array("-","/"), " ", $request[2]);
$id = $category->find_id_by_name($name);

你不需要向前斜杠。 尝试这个

$name = str_replace(array("-",'/'), " ", $request[2]));

尝试这个

$name = str_replace(array("-","/"), " ", $request[2]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM