簡體   English   中英

PHP正則表達式preg_replace

[英]PHP Regex preg_replace

我要替換此URI

http://localhost/prixou/index.php?page=list&category=1&sub=1&subsub=0&brand=Sony&toto=titi

通過這個URI

http://localhost/prixou/index.php?page=list&category=1&sub=1&subsub=0&kljklj=sdfsd

==>我要刪除“&brand = Sony”

我嘗試了這個:

preg_replace('/(^.*)(&brand=.*)(&.*)/', '$1$3', 'http://localhost/prixou/index.php?page=list&category=1&sub=1&subsub=0&brand=Sony&toto=titi');

但是它在特定情況下不起作用:URI中的參數“ toto”不存在的情況

所以如果我這樣做

preg_replace('/(^.*)(&brand=.*)(&.*)/', '$1$3', 'http://localhost/prixou/index.php?page=list&category=1&sub=1&subsub=0&brand=Sony'); 

它不起作用==>“&brand = Sony”仍然出現

那我該怎么辦?

我不會使用正則表達式。

首先,使用parse_url將url分成幾部分。
然后,在查詢部分上使用parse_str

對查詢鍵執行任何操作,然后將其重新組合。
生成查詢字符串: http_build_query
然后使用http_build_url構建url

 preg_replace("/\&brand=Sony/", "", $uri);

怎么樣:

preg_replace('/[\?&]brand=\w*/', '', $url);

如果您想獲得關鍵品牌的價值

preg_replace('/&?brand=[^&]+/i','',$url);
(^.*)(&brand=.*)(&.*)?

您可以添加?:

(^.*)(&brand=.*)(&.*)?

echo preg_replace(
'/(^.*)(&brand=.*)(&.*)?/', 
'$1$3', 
'http://localhost/prixou/index.php?page=list&category=1&sub=1&subsub=0&brand=Sony'); 

輸出:

http://localhost/prixou/index.php?page=list&category=1&sub=1&subsub=0

謝謝大家。 所以這是我的最終解決方案,它可以正常工作:

<?php
$actual_link = 'index.php?'.$_SERVER['QUERY_STRING']; //complete link of my page
$parsedURL= parse_url($actual_link);
parse_str($parsedURL["query"],$tabParametersQuery);    
$tabParametersQuery['brand']="";
$newURL = "index.php?".http_build_query($tabParametersQuery);
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM