0

我正在尝试用连字符替换 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转储

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

6 回答 6

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";
于 2013-05-01T09:33:28.303 回答
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]);
于 2013-05-01T09:50:21.687 回答
0

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

$name = str_replace(array('-','/'), " ", $request[2]);
$id = $category->find_id_by_name($name);
于 2013-05-01T09:33:51.417 回答
0

您不必转义“/”。反斜杠需要在这里转义,而不是正斜杠。

$name = str_replace(array("-","/"), " ", $request[2]);
$id = $category->find_id_by_name($name);
于 2013-05-01T09:34:26.127 回答
0

您不需要转义正斜杠。尝试这个

$name = str_replace(array("-",'/'), " ", $request[2]));
于 2013-05-01T09:35:32.490 回答
0

尝试这个

$name = str_replace(array("-","/"), " ", $request[2]);
于 2013-05-01T09:40:57.780 回答