如果有两个值(?),如何在php中格式化url


How to format url in php if have two value (?)

$url = 'http://test.com/?sort=newest&v=list?paged=3';

=> 如何将此网址preg_replace http://test.com/?sort=newest&v=list&paged=3

如果这是您需要编辑的唯一一种 url,我宁愿:

$str = str_replace("?", "&", $str);
$str = str_replace("&", "?", $str, 1);

因此,将所有 ? 更改为 &,然后仅将 & 的第一个匹配项更改回 ?。

如果你想显式使用preg_replace那么这将可以解决问题。

$url = preg_replace("/'?(.*?)('?)(.*?)/", "?$1&$3", $url);

这只会替换第一个问号之后的单个问号。如果你有更多,你可以重复它,直到只剩下一个问号。

while(substr_count($url, "?") > 1)
{
    $url = preg_replace("/'?(.*?)('?)(.*?)/", "?$1&$3", $url);
}

你可以获取$_SERVER['QUERY_STRING']的查询字符串,然后将?替换为&

   $str = $_SERVER['QUERY_STRING'];
   // $str = "sort=newest&v=list?paged=3?order=asc";
   $str = str_replace("?", "&", $str);
   echo $str;
   //output : sort=newest&v=list&paged=3&order=asc

这里有一个小函数:

function cleanUrl($url) {
    //Replace all ? to &
    $url = str_replace('?', '&', $url);
    //Get position of first &
    $posFirst = strpos($url, '&');
    //Replace first & with ?
    return substr_replace($url,'?',$posFirst,1);
}
$newUrl = cleanUrl('http://test.com/?sort=newest&v=list?paged=3');
var_dump($newUrl); //string(43) "http://test.com/?sort=newest&v=list&paged=3"

但我认为你有一个设计错误。可以创建参数数组,然后使用 http_build_query 生成查询字符串。

像这样的东西?

$url = 'http://test.com/?sort=newest&v=list?paged=3';
$purl = parse_url($url);
$purl["query"] = str_replace("?","&",$purl["query"]);   // replace all '?' except first
$url = $purl["scheme"]."://".$purl["host"].$purl["path"]."?".$purl["query"];
echo $url;
// output
// http://test.com/?sort=newest&v=list&paged=3