Home  >  Article  >  Backend Development  >  php正则过滤网址中一个参数,如何如何写

php正则过滤网址中一个参数,如何如何写

WBOY
WBOYOriginal
2016-06-13 13:09:31871browse

php正则过滤网址中一个参数,请教高手怎么怎么写?
有以下网址:

http://127.0.0.1/c/1.php?ft=x7cj
需过滤成:http://127.0.0.1/c/1.php

http://127.0.0.1/c/1.php?form=post&ft=gy4e
需过滤成:http://127.0.0.1/c/1.php?form=post

http://127.0.0.1/c/1.php?ft=7yd4r&form=post
需过滤成:http://127.0.0.1/c/1.php?form=post



比如用上面三种格式的网址打开以下php文件,如何用正则输出过滤出的效果?

$tjurl="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
//怎么用一句话正则过滤上面三种格式的网址?网址中参数“ft=*****”中的*****不是固定的字母或数字,随机变化的

echo "$tjurl";
 exit;
?>

------解决方案--------------------

PHP code
<?php $str = 'http://127.0.0.1/c/1.php?ft=x7cj

http://127.0.0.1/c/1.php?form=post&ft=gy4e

http://127.0.0.1/c/1.php?ft=7yd4r&form=post';
$str = preg_replace('/[\?&]ft=\w+/','',$str);
var_dump($str);
?>
<br><font color="#e78608">------解决方案--------------------</font><br>
PHP code
 $arr=array(
'http://127.0.0.1/c/1.php?ft=x7cj',
'http://127.0.0.1/c/1.php?form=post&ft=gy4e',
'http://127.0.0.1/c/1.php?ft=7yd4r&form=post'
);

print_r(array_map('foo',$arr));
function foo($url){
   $ar=parse_url($url);

   if(!isset($ar['query'])) return $url;
   
   parse_str($ar['query'],$arr);
   unset($arr['ft']);
   return $ar['scheme'].'://'.$ar['host'].$ar['path'].($arr ? '?'.http_build_query($arr) : '');
}
<br><font color="#e78608">------解决方案--------------------</font><br>
这样写(注释掉后面的$s可测试前面的)<br>$s = 'http://127.0.0.1/c/1.php?seed=add&ft=7yd4r&form=post';<br>$s = 'http://127.0.0.1/c/1.php?ft=x7cj';<br>$s = 'http://127.0.0.1/c/1.php?form=post&ft=gy4e';<br>$s = 'http://127.0.0.1/c/1.php?ft=7yd4r&form=post';<br><br><strong>echo preg_replace('/([?&])ft=[^&]+(&?)/e', '"$2"==""?"":"$1"', $s);</strong><br><br>人家给你弄个数组,只不过是让你测试起来方便些 <div class="clear">
                 
              
              
        
            </div>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article: PHP认证码兑现 Next article: 解析url的三个php函数