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

时间:2013-05-01 09:30:23

标签: php

我正在尝试用连字符替换空格并在URL中转发斜杠,例如www.example.com/car/ bmw / porsche 其中bmw / porsche是一个值..但它不是似乎正在为正斜线而努力。

这就是我所拥有的空间:

$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(" ", "/");这给了我以下内容: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)

6 个答案:

答案 0 :(得分:1)

您可以使用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";

答案 1 :(得分:1)

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]);

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

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

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

答案 4 :(得分:0)

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

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

答案 5 :(得分:0)

试试这个

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