簡體   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