开发者

preg_replace & regular expression help

开发者 https://www.devze.com 2023-04-03 22:40 出处:网络
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\";

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

0

精彩评论

暂无评论...
验证码 换一张
取 消