开发者

str_replace string in array number auto increasing

what we can do to remove page=2& From:

"page=2&param1=value1&param2=value2" or
"param1=value1&page=2&param2=value2".开发者_如何学Python

become:

"param1=value1&param2=value2" or
"param1=value1&param2=value2".

in case of page=2, 2 is any natural no. i.e. (0 to 32000).

Regards,


You can use parse_str to parse the string to an array, unset page from the array, and then use http_build_query to reconstruct the result.

Code example:

$str = 'page=2&param1=value1&param2=value2';
$arr = array();
parse_str($str, $arr);
unset($arr['page']);
echo http_build_query($arr);


 $str = trim(preg_replace("/\bpage=\d+&?/", "", $str), "$");

The regexp:

\b        # Match a "boundary" point (start of new word)
page=     # Match 'page='
\d+       # Match 1 or more digits
&?        # Match a '&' if it exists

The trim around the outside will remove any trailing & that might be leftover.

If you want to trim anything you can replace the \d+ with [^&]+ to match any characters other than &.

 $str = trim(preg_replace("/\bpage=[^&]+&?/", "", $str), "$");


using explode ?

$urlString = "page=2&param1=value1&param2=value2";
$arr = explode('&',$urlString);
print_r( $arr );
foreach( $arr as $var => $val ) {
    if( substr( $val, 0, 6 ) == 'param2' ) {
        unset( $arr[ $var ] );
    }
}
$urlString = implode('&',$arr);


If I understood you correctly, this will let you remove an arbitrary page (as long as you know the number):

function replacePage($querystring, $page = 1) {
    return str_replace('page='.$page.'&', '', $querystring);
} 

As a side note, using regular expressions is not the optimum way to code if they can be avoided. They are slow and should be replaced with other methods such as str_replace or tokenizing where possible. Personally I'd use my method If I knew what page I had to remove from the query string as it will run much faster than a preg_replace.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜