使用substr_replace进行url路径操作

时间:2014-08-07 12:10:09

标签: php

使用此代码,我试图操纵网址的路径。被操纵的URL不包括“://”部分。它返回httpdomain.com/string/4607120765.html而不是http://domain.com/string/4607120765.html。我正在寻找能纠正这个问题的php函数。

<?php
 $url = "http://domain.com/sfv/4607120765.html";
 $url = parse_url($url);
 $url['path'] = substr_replace($url['path'], "string", 1, 3);
 $url = implode($url);
 echo $url;
?>

http://domain.com/sfv/4607120765.html needs to be changed to http://domain.com/string/4607120765.html

3 个答案:

答案 0 :(得分:0)

implode之前添加一行,如下所示

$url['scheme'] = $url['scheme']."://";

修改后的代码

<?php
 $url = "http://domain.com/sfv/4607120765.html";
 $url = parse_url($url);
 $url['path'] = substr_replace($url['path'], "string", 1, 3);
 $url['scheme'] = $url['scheme']."://"; // add this line
 $url = implode($url);
 echo $url;
?>

答案 1 :(得分:0)

要在字符串中替换第一个且仅出现第一个://:

$url = preg_replace('#://#','',$url,1);

我使用#而不是模式中的common /所以我不必逃避/。最后的1意味着“只替换第一个。”

答案 2 :(得分:0)

试试这个功能。

/***
 * $url : url to parse
 * $replace_string : String to replace
 * $count_replace : Number of replacement 
 */
function url_path_replace($url,$replace_string,$count_replace)
 {
     //check if valid url
     if(!filter_var($url, FILTER_VALIDATE_URL)){
         throw new Exception("Invalid url.");
     }

     $url_parsed = parse_url($url);
     debug($url_parsed);
     $scheme   = isset($url_parsed['scheme']) ? $url_parsed['scheme'] . '://' : '';
     $host     = isset($url_parsed['host']) ? $url_parsed['host'] : '';
     $port     = isset($url_parsed['port']) ? ':' . $url_parsed['port'] : '';
     $user     = isset($url_parsed['user']) ? $url_parsed['user'] : '';
     $pass     = isset($url_parsed['pass']) ? ':' . $url_parsed['pass']  : '';
     $pass     = ($user || $pass) ? "$pass@" : '';
     $path     = isset($url_parsed['path']) ? $url_parsed['path'] : '';
     $query    = isset($url_parsed['query']) ? '?' . $url_parsed['query'] : '';
     $fragment = isset($url_parsed['fragment']) ? '#' . $url_parsed['fragment'] : '';
     if($scheme==''){
         //not a valid url
         throw new Exception("Invalid url.");
     }
     if($path!=""){
        $exploded_path = explode("/", $path);
        $exploded_path = array_filter($exploded_path);//filtering any null values

        $exploded_path = array_splice($exploded_path, $count_replace);

        $path = "/".$replace_string."/".implode($exploded_path,"/");
     }

     return "$scheme$user$pass$host$port$path$query$fragment"; 
 }

在你的情况下给予

echo url_path_replace("http://domain.com/sfv/4607120765.html","string",1);