2013-03-21 56 views
0

我想这个URI来替换这个URIPHP正则表达式的preg_replace

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

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

==>我要删除 “&品牌=索尼”

我尝试这样做:

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

bu t将其不特定的情况下工作:的情况下在URI参数“TOTO”不存在

所以,如果我做

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

它不工作==>“ &品牌=索尼“仍然出现

那么我该怎么办?

+0

你没有指定'preg_replace'到任何结果,因此它被执行后基本丧失。 – 2013-03-21 17:29:29

回答

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

我不会使用正则表达式。

首先,使用parse_url将网址拆分为小块和小块。
然后,在查询部分使用parse_str

做任何你想要的查询键,然后把它全部结合起来。
要构建查询字符串返回:http_build_query
然后建立使用url http_build_url

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

这是不好的,如果品牌是第一个参数后?并不是 &。 – Adidi 2013-03-21 17:40:32

+0

好点感谢 – suspectus 2013-03-21 17:41:07

0

如何:

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

这就是如果你想删除任何品牌。如果你只想删除索尼,那么嫌疑人的答案是正确的。 – ezeedub 2013-03-21 17:35:12

+0

如果品牌价值包含的字符不是一个单词 - 比如#或其他东西,这不是一个好的解决方案。对于它的解决方案是任何字符不是下一个参数& - [^&] +像我的解决方案:)和平 – Adidi 2013-03-21 17:38:23

+0

好点。你应该检查'&'或'?'太。但实际上我们都错了,错位是正确的。 – ezeedub 2013-03-21 18:34:45

0

如果你想要的关键品牌价值

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

这不提供问题的答案。要批评或要求作者澄清,请在其帖子下方留言。 – 2013-03-21 17:53:12

+0

这只是最后一个问号的原始正则表达式,它可以解决问题。 – 2013-03-21 18:52:49

0

你可以添加:

(^.*)(&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