douhan4093 2013-05-01 09:30
浏览 67
已采纳

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

I am trying to replace a space and forward slash in a url with a hyphen e.g www.example.com/car/bmw/porsche where bmw/porsche is one value..but it doesn't seem to be working for the forward slash.

This is what I have for the space which works:

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

But when I add it for the forward slash, it doesn't work.. although it still works for the space:

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

How would I change this to work?

EDIT

So I changed the code to the following:

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

Then I put the $char in an array like this $char = array(" ", "/"); Which gave me the following: Notice: Array to string conversion Then I tried getting them by their indexes like this:

$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 

I just can't seem to get them to work together :(


[NEW EDIT]

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条回答 默认 最新

  • douqun1977 2013-05-01 09:33
    关注

    You could use urlencode() for this:

    $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;
    

    You could use urldecode() to retreive it:

    echo $request[2]; // Results in "Bmw%2FPorsche"
    $myUri = urldecode($request[2]); // Results in "Bmw/Porsche";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试