在php中按不同的模式拆分多个部分的字符串(url)

时间:2014-02-28 10:46:38

标签: php arrays explode

我有以下字符串

$searchlink = 'search-all.php?page=1&MakeId=BMW&BodyId=Coupe&ModelId=320&PriceToId=%C2%A3+20000&PriceFromId=%C2%A3+100&FuelId=Diesel&MilageId=%26gt%3B5000+miles+&DistanceId=%26gt%3B10+miles&AgeId=%26gt%3B1+years&postcodeId=&keywordId=&TransmissionId=Automatic&Search=Finddata';

我尝试使用explode将其拆分为=:

$searchlink = explode('=', $searchlink);

并且这导致了var_dump

array(15) { 
  [0]=> string(19) "search-all.php?page" 
  [1]=> string(8) "1&MakeId" 
  [2]=> string(10) "BMW&BodyId" 
  [3]=> string(13) "Coupe&ModelId" 
  [4]=> string(13) "320&PriceToId" 
  [5]=> string(24) "%C2%A3+20000&PriceFromId" 
  [6]=> string(17) "%C2%A3+100&FuelId" 
  [7]=> string(15) "Diesel&MilageId" 
  [8]=> string(30) "%26gt%3B5000+miles+&DistanceId" 
  [9]=> string(22) "%26gt%3B10+miles&AgeId" 
 [10]=> string(26) "%26gt%3B1+years&postcodeId" 
 [11]=> string(10) "&keywordId" 
 [12]=> string(15) "&TransmissionId" 
 [13]=> string(16) "Automatic&Search" 
 [14]=> string(8) "Finddata"

所以我尝试在爆炸后基于&进行另一次爆炸,但结果是NULL。像$searchlink = explode('&', $searchlink)一样试过smth。

我的最终代码是:

<?php
$searchlink = 'search-all.php?page=1&MakeId=BMW&BodyId=Coupe&ModelId=320&PriceToId=%C2%A3+20000&PriceFromId=%C2%A3+100&FuelId=Diesel&MilageId=%26gt%3B5000+miles+&DistanceId=%26gt%3B10+miles&AgeId=%26gt%3B1+years&postcodeId=&keywordId=&TransmissionId=Automatic&Search=Finddata';
$searchlink = explode('=', $searchlink);
$searchlink = explode('&', $searchlink);
?>

预期的产出是 BMW 320 Coupe PricefromId 100 PricetoId 20000 FuelId Diesel MilageId 5000 DistanceId 10 AgeId 1 PostocodeId KeywordId TransmissionId Automatic.

请帮我解决这个问题。非常感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

发现parse_str()

$searchlink = 'search-all.php?page=1&MakeId=BMW&BodyId=Coupe&ModelId=320&PriceToId=%C2%A3+20000&PriceFromId=%C2%A3+100&FuelId=Diesel&MilageId=%26gt%3B5000+miles+&DistanceId=%26gt%3B10+miles&AgeId=%26gt%3B1+years&postcodeId=&keywordId=&TransmissionId=Automatic&Search=Finddata';
parse_str($searchlink, $result);
//var_dump($result);