简体   繁体   中英

PHP Regex preg_replace

I want to replace this URI

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

by this URI

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

==> I want to delete "&brand=Sony"

I tried this :

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

but it doesn't work in a specific case : the case where the parameter "toto" in the URI doesn't exist

So if I do

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

It doesn't work ==> "&brand=Sony" still appear

So how can I do ?

I wouldn't use regular expressions.

First, use parse_url to split the url into its bits and pieces.
Then, use parse_str on the query portion.

Do whatever you want to the query keys, then combine it all back.
To build the query string back: http_build_query
Then build the url using http_build_url

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

怎么样:

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

如果您想获得关键品牌的价值

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

you can just add ?:

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

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

output:

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

Thank you everybody. So here is my final solution and it works fine :

<?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);
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM