preg_replace & regular expression help
A friend helped us with this line of code a while back, and I'm trying to get it to work for this:
$curPageUrl = "http://www.site.com/index.php?sort=a";
$currentPage = preg_replace("/&sort=\w+/", "", $curPageUrl);
echo $currentPage; // http://www.site.com/index.php?sort=f?sort=a?sort=z
For example, $curPageUrl
gets the clients page they are on and then it passes it through this.
Basically, we want $currentPage
to strip off:
?sort=a
?sort=f
?sort=z
fr开发者_开发技巧om the $curPageUrl
I hope my example helped.
Thank you.
preg_replace("/(\?|\&)sort=\w+/", "", $curPageUrl);
It will accept '&' or '?'.
<?php
$tests = array(
"http://www.site.com/index.php",
"http://www.site.com/index.php?sort=a",
"http://www.site.com/index.php?foo=bar&sort=a",
"http://www.site.com/index.php?foo=bar&sort=a&bla=baz",
"http://www.site.com/index.php?sort=a&bla=baz"
);
foreach($tests as $test) {
echo preg_replace(
array('@\?sort=[^&]*@', '@&sort=[^&]*@'),
array('?', ''),
$test
);
echo PHP_EOL;
}
preg_replace("/\?sort=\w+/", "", $curPageUrl);
精彩评论